【问题标题】:Nodejs post request variable scope issueNodejs发布请求变量范围问题
【发布时间】:2020-06-21 06:26:32
【问题描述】:

我对 Nodejs 有点陌生。 在以下代码中,我从 API 获取数据。

request.post({ url:endpoint, form: requestParams }, function (err, response, body) {
    if (err) {
        console.log("Error = " + err);
    }
    else {
        let parsedBody = JSON.parse(body);
        if (parsedBody.error_description) {
            console.log("Error = " + parsedBody.error_description);
        }
        else {
            // testFunc(AccessToken);
            test = "Success!";
            testFunc(test);
        }
    }
});

function testFunc(success){
    Token = success;
    console.log(Token);
}

// this code gives the error "Token is not defined" \/
console.log(Token);

在发布请求中,我将变量设为“test”。我希望能够将其用作全局变量,以便在获取请求中使用它。

当我在“testFunc”中console.log()“Token”时,它会正确记录它。 但是当我在函数之外console.log() 时,它会给出错误Token is not defined

如何将“Token”或“test”变量设为全局变量,以便在另一个 get 请求中使用它?

提前致谢!

【问题讨论】:

    标签: node.js variables post scope global-variables


    【解决方案1】:

    您的 request.post 正在异步运行 你可以使用 request-promise 库

    const request = require("request-promise"); 
    

    改成

    var result = await request(options);
    

    或了解更多知识阅读这篇文章 https://blog.risingstack.com/mastering-async-await-in-nodejs/

    【讨论】:

      【解决方案2】:

      您的TokentestFunc 上的局部变量

      function testFunc(success){
          Token = success;
          console.log(Token);
      }
      

      尝试将Token 定义为全局变量 您可以在所有 import require(...) 或以上 request.post

      let Token; //this is global declared variable
      

      还有你的console.log 不能和你的代码一样

      作为你的问题I want to be able to use this as a global variable so i can use it in a get request.

      所以你需要把你的console.log放在request.get里面

      类似

      request.get('xxxxxx', , function(err) {
          console.log("Token is " , Token);
      });
      
      
      

      【讨论】:

      • 使变量成为全局变量对我不起作用。我在request.post 上方添加了let Token;,但console.log(Token) 返回undefined。我没有将console.log() 放在request.get 中的原因只是为了测试,因为我无法访问request.post 之外的变量,我认为我也无法在@ 中访问它987654338@
      • 您的request.post 正在异步运行。这意味着即使Token 也没有赋值,你在下面的console.log 已经执行了,这就是你得到未定义的原因
      猜你喜欢
      • 1970-01-01
      • 2015-03-01
      • 1970-01-01
      • 2020-02-29
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多