【问题标题】:Unable to access response object data outside the function in node js无法访问节点js中函数之外的响应对象数据
【发布时间】: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


【解决方案1】:

使用承诺。

您可以尝试以下操作:

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));

【讨论】:

  • 它给了我apiCall.then 不是函数的错误
  • 对不起。做 apiCall().then。编辑了我的答案
猜你喜欢
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 2014-11-01
  • 2015-04-29
  • 2021-01-11
相关资源
最近更新 更多