Why does my sailsjs service return “undefined” to the calling controller action?

落爺英雄遲暮 提交于 2019-12-13 04:43:23

问题


I have to POST to an API that someone else has developed in order to obtain an authorization code, and as I have to do it in several different contexts I thought I'd move the code for handling the POST and getting the response to a service.

The frustrating thing at the moment is that I seem to be getting back the value that I want from the API, but can't return it from the server to the calling sails controller.

Here's the service source code:

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();
  }
}

And here's two relevant lines from my controller action:

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

The weird thing is that the controller console log gets written before the service one does:

vc=undefined
code=YoAr3ofWRIFGpoi4cRRehP3eH+MHYo3EogvDNcrNDTc=

Any ideas? I have a much simpler service running (just some string manipulation stuff); I have a feeling the issue here relates to the asynchronous nature of the API request and response.


回答1:


Jasper, your correct in your assumption that it is the " asynchronous nature of the API request and response".

When you execute your http call in your verify service, node makes that call and them moves on to the rest of the code console.log('vc='+vc); and does not wait for the http call to finish.

I'm not sure what your end result should be but you can rewrite your controller / service to include the callback (this is just one options, there are many ways to do this of course, other people should suggest others)

verify.js

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

then in your controller controller.js

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


来源:https://stackoverflow.com/questions/26192566/why-does-my-sailsjs-service-return-undefined-to-the-calling-controller-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!