【问题标题】:Getting undefined returned from javascript function in nodejs [duplicate]从nodejs中的javascript函数返回未定义[重复]
【发布时间】:2017-12-13 14:57:24
【问题描述】:

我在 auth.js 中有以下代码

let request = require("request");


   function getToken(callback) {

    let options = { method: 'POST',
      url: 'https://testsite/openid-connect/token',
      headers: 
      { 
        'content-type': 'application/x-www-form-urlencoded'
      },
      form: 
      { 
        grant_type: 'password',
        username: 'admin',
        password: 'password',
        client_id: '123' 
        } 
      };
      request(options, function (error, response, body) {
      if (error) throw new Error(error);
      callback(body.access_token);
    });
  }

module.exports = {
  getToken,
};

我从另一个 index.js 文件中调用方法 getToken 为

let authServ = require('./auth');
const token = authServ.getToken();
console.log(token);

但我在变量“token”中返回“undefined”,而不是实际的token。有人可以帮助我在哪里做错了吗?

【问题讨论】:

  • 您正在发送回调。使用它(:
  • 我不知道你在期待什么。 getToken() 没有返回值,访问异步检索令牌的唯一方法是使用函数所需的回调。

标签: node.js callback promise request


【解决方案1】:

您必须将回调传递给函数 getToken

let authServ = require('./auth');
authServ.getToken(function(token) {
   console.log(token);
});

【讨论】:

  • 即使在实现了上述代码之后,这也不起作用。问题出在请求方法调用内部的回调中。如果回调被放置在 request() 调用之外,那么我可以取回该值。
猜你喜欢
  • 1970-01-01
  • 2013-06-26
  • 2014-03-05
  • 2016-05-20
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多