Nodejs 请求返回行为异常 [英] Nodejs Request Return Misbehaving

查看:38
本文介绍了Nodejs 请求返回行为异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题.在过去的 3 个小时里,我一直在努力解决这个问题,但我不知道为什么这不符合我的预期.请注意,我对 Javascript 还是很陌生,所以如果有任何明显明显的地方,我深表歉意.

I have a question. I've been trying to figure this out for the past 3 hours now, and I have no clue as to why this isn't working how i'm expecting it to. Please know that i'm still very new to Javascript, so I apologise if anything is blatantly obvious.

使用此代码,我试图从 Twitter 获取不记名令牌,但是,return bodyconsole.log(body) 返回 2 个完全不同的东西.

With this code, i'm trying to get a bearer token from Twitter, however, return body and console.log(body) return 2 completely different things.

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

When I console.log(body), I get the output I expect:

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

但是,如果我返回正文,我会收到 JSON 格式的 http 请求.我在下面粘贴了我的代码,希望有人能够提供帮助.

However, if I return body, I get the http request as JSON. I've pasted my code below, I hope someone will be able to help.

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)

推荐答案

异步,异步,异步.

不能从函数返回异步操作的结果.该函数早在调用异步回调之前就已返回.因此,使用 request.post() 结果的唯一地方是在回调本身内部,并通过从该回调中调用其他一些函数并将数据传递给该其他函数.

You cannot return the results of an asynchronous operation from the function. The function has long since returned before the asynchronous callback is called. So, the ONLY place to consume the result of your request.post() is INSIDE the callback itself and by calling some other function from within that callback and passing the data to that other function.

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 开发人员来说,这是一个非常常见的学习问题.要在 node 中编码,您必须学习如何使用这样的异步回调.

FYI, this is a very common learning issue for new node.js/Javascript developers. To code in node, you have to learn how to work with asynchronous callbacks like this.

这篇关于Nodejs 请求返回行为异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆