Nodejs请求返回行为不端

时间:2015-09-07 06:26:52

标签: javascript node.js http twitter request

我有一个问题。我过去3个小时一直试图解决这个问题,而且我也不知道为什么我的工作没有达到预期效果。请知道我对Javascript还是一个新手,所以如果有任何明显的事情,我会道歉。

使用此代码,我试图从Twitter获取持有人令牌,但是,return bodyconsole.log(body)会返回2个完全不同的内容。

当我console.log(body)时,我得到了我期望的输出:

{"token_type":"bearer","access_token":"#####"}

但是,如果我return body,我会将http请求作为JSON获取。我在下面粘贴了我的代码,希望有人能够提供帮助。

var request = require('request');

var enc_secret = new Buffer(twit_conkey + ':' + twit_consec).toString('base64');
var oauthOptions = {
    url: 'https://api.twitter.com/oauth2/token',
    headers: {'Authorization': 'Basic ' + enc_secret, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
    body: 'grant_type=client_credentials'
};

var oauth = request.post(oauthOptions, function(e, r, body) {
    return body;
});

console.log(oauth)

1 个答案:

答案 0 :(得分:1)

异步,异步,异步。

您无法从函数返回异步操作的结果。该函数早在调用异步回调之前就已返回。因此,消耗request.post()结果的唯一位置是在回调本身内部,并通过从该回调中调用其他函数并将数据传递给其他函数。

var oauth = request.post(oauthOptions, function(e, r, body) {
    // use the result here
    // you cannot return it
    // the function has already returned and this callback is being called
    // by the networking infrastructure, not by your code

    // you can call your own function here and pass it the async result
    // or just insert the code here that processes the result
    processAuth(body);
});

// this line of code here is executed BEFORE the callback above is called
// so, you cannot use the async result here

仅供参考,对于新的node.js / Javascript开发人员来说,这是一个非常常见的学习问题。要在节点中编码,您必须学习如何使用这样的异步回调。