简体   繁体   English

从node.js中的request.end()检索数据

[英]Retrieve data from request.end() in node.js

I want to use result of unirest request to another file in Node.js but I can not get data from request.end() function to outer variable. 我想对Node.js中的另一个文件使用unirest请求的结果,但是我无法从request.end()函数获取数据到外部变量。

Code is below: 代码如下:

request.end(function (response) {
        if(response.error) {
            console.log("AUTHENTICATION ERROR: ", response.error);
        } else {
            callback(null, response.body);
        }

        console.log("AUTHENTICATION BODY: ", response.body);
    });

var result = authentication(function(error, response) {
    var authenticationToken = response.access_token;

    if(authenticationToken != null) {
        console.log("Token: ", authenticationToken);

        return authenticationToken;
    }
});

I want to get authenticationToken value to export with module.exports for another modules. 我想获取authenticationToken值以与module.exports一起导出另一个模块。

I am using unirest http library . 我正在使用unirest http库

its a callback function, and is treated as parameter, not a function that returns value. 它是一个回调函数,被视为参数,而不是返回值的函数。

You can do this though: 您可以这样做:

var result;
authentication(function(error, response) {
    var authenticationToken = response.access_token;

    if(authenticationToken != null) {
        console.log("Token: ", authenticationToken);

        module.exports.result = authenticationToken; // setting value of result, instead of passing it back
    }
});

you can use result variable now. 您现在可以使用result变量。 But be careful, its an asynchronous function, so you may not be able to use it immediately, until a value is assigned to it, within a callback function. 但请注意,它是一个异步函数,因此在回调函数中,您可能无法立即使用它,直到为其分配了值。

To export result value: 导出结果值:

module.exports.result = null;

Example

m1.js m1.js

setTimeout(() => {
   module.exports.result = 0;
}, 0);

module.exports.result = null;

app.js app.js

const m1 = require('./m1.js');

console.log(JSON.stringify(m1));

setTimeout(() => {
  console.log(JSON.stringify(m1));

}, 10);

Output 输出量

{"result":null}
{"result":0}

so you can keep using variable result , once the variable is assigned it would contain the value. 因此,您可以继续使用变量result ,一旦分配了变量,它将包含该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM