【发布时间】:2015-11-19 14:14:42
【问题描述】:
我不知道如何从 node.js 模块中获取变量。我正在创建一个与身份验证机制交互的模块,目前它只返回一个令牌。我在 main.js 中需要这个令牌,因为我将调用其他模块,并传递这个令牌进行身份验证。
//auth.js
var request = require("request");
var authModule = {};
var authToken = "";
var options = {
method: 'POST',
url: 'https://dummy.url/oauth/token',
headers: {
'authorization': 'Basic secretkeystring',
'accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded'
},
form: {
grant_type: 'password',
username: 'indegomontoya',
password: 'sixfingeredman'
}
};
authModule.getToken = function getToken(){
request(options, requestToken);
};
function requestToken (error, response, body) {
if (error) throw new Error(error);
authToken = response.body.toString().split('\n')[1].split(":")[1].split('"')[1];
console.log("auth.js says: " + authToken);
// ^^ this works, and spits out the correct token to the console
return authToken;
};
module.exports = authModule;
module.exports.token = authToken;
这是我的 main.js:
//main.js
var auth = require("./auth.js");
var token;
token = auth.getToken();
console.log("main.js says :"+ token);
// ^^ comes back undefined
我见过将变量从 main.js 发送到 module.js 的示例,但我需要做相反的事情。非常感谢任何帮助!
编辑:代码中的错字。
【问题讨论】:
-
我相信,因为它是异步的,你会想要一个回调。 callbackhell.com 对我的理解帮助很大。
标签: javascript node.js