Friday 15 August 2014

node.js - Why does my sailsjs service return "undefined" to the calling controller action? -



node.js - Why does my sailsjs service return "undefined" to the calling controller action? -

i have post api else has developed in order obtain authorization code, , have in several different contexts thought i'd move code handling post , getting response service.

the frustrating thing @ moment seem getting value want api, can't homecoming server calling sails controller.

here's service source code:

module.exports = { getverifycode: function(uuid, ip_addr) { console.log (uuid); console.log (ip_addr); var http = require('http'), querystring = require('querystring'), // info send send_data = querystring.stringify({ uuid : uuid, ip_addr : ip_addr }), // options posting 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); homecoming ('vc='+verify_code); }); }); post_req.write(send_data); post_req.end(); } }

and here's 2 relevant lines controller action:

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

the weird thing controller console log gets written before service 1 does:

vc=undefined code=yoar3ofwrifgpoi4crrehp3eh+mhyo3eogvdncrndtc=

any ideas? have much simpler service running (just string manipulation stuff); have feeling issue here relates asynchronous nature of api request , response.

jasper, right in assumption " asynchronous nature of api request , response".

when execute http phone call in verify service, node makes phone call , them moves on rest of code console.log('vc='+vc); , not wait http phone call finish.

i'm not sure end result should can rewrite controller / service include callback (this 1 options, there many ways of course, other people should suggest others)

verify.js

getverifycode: function(uuid, ip_addr, cb) { // bunch of stuff homecoming post_req = http.request(options, cb(post_res}); }

then in controller controller.js

verify.getverifycode(req.session.uuid, req.connection.remoteaddress, function(resps){ // code in here execute when http phone call finished })

node.js function service express sails.js

No comments:

Post a Comment