为什么我的sailsjs服务返回" undefined"到呼叫控制器的动作?

时间:2014-10-04 11:56:31

标签: node.js function service express sails.js

我必须POST一个其他人已经开发的API以获取授权代码,因为我必须在几个不同的上下文中执行它,我以为我会移动代码来处理POST并获得响应服务。

目前令人沮丧的是,我似乎从API中获取了我想要的值,但无法将其从服务器返回到调用sails控制器。

这是服务源代码:

module.exports = {
  getVerifyCode: function(uuid, ip_addr) {
    console.log (uuid);
    console.log (ip_addr);
    var http = require('http'),
    querystring = require('querystring'),
    // data to send
    send_data = querystring.stringify({
      uuid : uuid,
      ip_addr : ip_addr 
    }),
    // options for posting to api
    options = {
      host: sails.config.api.host,
      port: sails.config.api.port,
      path: '/verifyCode/update',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(send_data)
      }
    },
    json_output = "",
    // post request
    post_req = http.request(options, function(post_res) {
      post_res.on('data', function(chunk) {
        json_output += chunk;
      });
      post_res.on('end', function() {
        var json_data = JSON.parse(json_output),
        verify_code = json_data.verify_code;

        console.log("code="+verify_code);
        return ('vc='+verify_code);
      });
     });
    post_req.write(send_data);
    post_req.end();
  }
}

这是我的控制器动作的两个相关行:

    var vc = verify.getVerifyCode(req.session.uuid, req.connection.remoteAddress);
    console.log('vc='+vc);

奇怪的是控制器控制台日志在服务之前写入:

vc=undefined
code=YoAr3ofWRIFGpoi4cRRehP3eH+MHYo3EogvDNcrNDTc=

有什么想法吗?我有一个更简单的服务运行(只是一些字符串操作的东西);我觉得这里的问题与API请求和响应的异步性有关。

1 个答案:

答案 0 :(得分:0)

Jasper,您认为这是“API请求和响应的异步特性”是正确的。

当您在verify服务中执行http调用时,节点会进行该调用,然后它们会转到代码的其余部分console.log('vc='+vc);,并且不会等待http调用完成。

我不确定你的最终结果是什么,但你可以重写你的控制器/服务以包含回调(这只是一个选项,当然有很多方法可以做到这一点,其他人应该建议其他人)< / p>

verify.js

getVerifyCode: function(uuid, ip_addr, cb) {
    // Bunch of stuff
    return post_req = http.request(options, cb(post_res});
}

然后在您的控制器中 controller.js

verify.getVerifyCode(req.session.uuid, req.connection.remoteAddress, function(resps){
    // code in here to execute when http call is finished
})