0

I have following code in 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,
};

and I'm calling the method getToken from another index.js file as

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

but I get "undefined" returned in variable "token" instead of the actual token. Can someone please help where I'm doing wrong?

Abhay
  • 57
  • 2
  • 8
  • you are sending a callback. use it(: – Amit Wagner Dec 13 '17 at 15:00
  • I don't know what you're expecting. `getToken()` has no return value and the ONLY way to get access to the asynchronously retrieved token is to use the callback that the function requires. – jfriend00 Dec 13 '17 at 15:28

1 Answers1

0

You have to pass a callback to the function getToken

let authServ = require('./auth');
authServ.getToken(function(token) {
   console.log(token);
});
David Vicente
  • 3,091
  • 1
  • 17
  • 27
  • This doesn't work even after implementing above code. The issue is in the callback which is inside request method call. If the callback is placed outside request() call then I'm able to get the value back. – Abhay Dec 13 '17 at 22:22