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

时间:2018-04-09 10:45:01

标签: javascript node.js http httprequest unirest

我想在 Node.js 中使用对另一个文件的unirest请求结果,但是我无法将 request.end()函数中的数据提供给外部变量。< / p>

代码如下:

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

我希望将 authenticationToken 值导出为module.exports以用于其他模块。

我正在使用 unirest http library

1 个答案:

答案 0 :(得分:0)

它是一个回调函数,被视为参数,而不是返回值的函数。

你可以这样做:

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

您现在可以使用result变量。 但要小心,它是一个异步函数,所以你可能无法立即使用它,直到在回调函数中为它赋值。

要导出结果值:

module.exports.result = null;

实施例

m1.js

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

module.exports.result = null;

app.js

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

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

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

}, 10);

输出

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

所以你可以继续使用变量result,一旦赋值变量,它就会包含值。