【发布时间】:2018-09-10 13:06:10
【问题描述】:
我正在使用node js并调用spotify API并在body对象中接收响应,如下代码所示:
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
console.log(body)
});
但是现在当我尝试访问函数外部的 body 对象时,我得到了未定义的结果。我认为问题在于我正在进行异步调用,因此在收到响应之前,执行了我在函数外使用 body 变量的语句。但是我对如何找到解决方案有点困惑。
感谢任何帮助
编辑:
request.get(options, function(error, res, body) {
console.log(body)
response.render('user_account.html', {
data: body
})
});
它给出了输出:
【问题讨论】:
-
你是对的,你只能在回调本身中访问
body变量,或者在你传递变量的函数中。 -
@LucaKiebel 那么我该怎么做才能在函数之外访问它。我想在我的 html 页面上显示数据。所以,我尝试使用
response.render()并通过,但它给出了 response.render() 不是函数的错误 -
您能否分享更多该代码块,显示哪个部分会产生
response.render() is not a function错误?
标签: node.js synchronization spotify