我必須發佈到其他人開發的API才能獲得授權代碼,因爲我必須在幾個不同的上下文中執行此操作,所以我想移動代碼以處理POST並獲得響應一項服務。爲什麼我的sailsjs服務對調用控制器的操作返回「undefined」?
此刻令人沮喪的事情是,我似乎正在從API獲取我想要的值,但無法將其從服務器返回到調用的sail控制器。
這裏的服務代碼:
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請求和響應的異步性質。
沒有人再.... :( – jasper 2014-10-05 09:49:21