2014-10-04 31 views
0

我必須發佈到其他人開發的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請求和響應的異步性質。

+0

沒有人再.... :( – jasper 2014-10-05 09:49:21

回答

0

賈斯珀,你的假設是正確的,它是「API請求和響應的異步性質」。

當您在verify服務中執行您的http呼叫時,節點發出該呼叫,並且他們轉移到代碼console.log('vc='+vc);的其餘部分,並且不等待http呼叫完成。

我不確定你的最終結果應該是什麼,但你可以重寫你的控制器/服務來包含回調(這只是一個選項,當然有很多方法可以做到這一點,其他人應該建議其他人)

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 
}) 
+1

謝謝在正確的方向碰撞! [這篇文章](https://github.com/maxogden/art-of-node#callbacks)也有幫助。我最終做了類似於你的建議。 – jasper 2014-10-07 04:12:35

相關問題