无法访问节点js中函数外的响应对象数据
Unable to access response object data outside the function in node js
我正在使用节点 js 并调用 spotify API 并在正文对象中接收响应,如下面的代码所示:
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 对象时,我得到了未定义的信息。我认为问题是我正在进行异步调用,因此在收到响应之前,我在函数外部使用主体变量的语句被执行。但是我对如何找到解决方案有点困惑。
感谢任何帮助
编辑:
request.get(options, function(error, res, body) {
console.log(body)
response.render('user_account.html', {
data: body
})
});
它给出了输出:
使用承诺。
您可以尝试以下操作:
const apiCall = () => {
return new Promise((resolve, reject) => {
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
if(error) reject(error);
console.log(body);
resolve(body);
});
});
}
apiCall().then((body) => {
// do your things here
})
.catch((err) => console.log(err));
我正在使用节点 js 并调用 spotify API 并在正文对象中接收响应,如下面的代码所示:
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 对象时,我得到了未定义的信息。我认为问题是我正在进行异步调用,因此在收到响应之前,我在函数外部使用主体变量的语句被执行。但是我对如何找到解决方案有点困惑。
感谢任何帮助
编辑:
request.get(options, function(error, res, body) {
console.log(body)
response.render('user_account.html', {
data: body
})
});
它给出了输出:
使用承诺。
您可以尝试以下操作:
const apiCall = () => {
return new Promise((resolve, reject) => {
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
if(error) reject(error);
console.log(body);
resolve(body);
});
});
}
apiCall().then((body) => {
// do your things here
})
.catch((err) => console.log(err));