0

I am using request module to return values . {code}

var token;
const request = require('request');
const authKey='Bearer <APPKEY>'
const ContentType='application/x-www-form-urlencoded' ;
var postData={
    'grant_type':'client_credentials'
};
const options = {
    url: '<m/c detils>',
    method: 'POST',
    headers: {
        'Content-Type': ContentType,
        'Authorization':authKey
    },
    body:require('querystring').stringify(postData)
};

module.exports.getAccessToken=request(options, function(errror, response, body){
    console.info("Token is caling");
    // body...


        console.info("inside request module----------------------",JSON.parse(body));
        console.info("response details---------------------",response);
        token= JSON.parse(body).access_token;
       console.info("token1---------------------",token);
       return token;


   })
)

{code}

Here I am able to return value for token ,but same thing if I want to use in another file for eg ::

var token = authtoken.getAccessToken;

I am getting value as undefined ,I have did

var authtoken=require('./utils/Utils.js');

Please help me out here

Shilpa
  • 103
  • 1
  • 9

3 Answers3

0

Your getAccessToken export isn't exporting a function, it's exporting the request result, which is, as Paul commented, not going to be defined.

I suspect what you wanted was to export a function that invokes the request, like this...

module.exports.getAccessToken = callback => request(options, function(error, response, body) {
   token= JSON.parse(body).access_token;
   callback(token);
});

Of course, you'll need to handle errors...

Jim B.
  • 4,512
  • 3
  • 25
  • 53
0

Since 'request' is async, you'd need to modify your code

// file 1
module.exports.getAccessToken = function (cb) {
    request(options, function(errror, response, body) {
        /**
         * do something
         */
        return cb(body.access_token)
    })
}

// file 2
const file1 = require('file1')

file1.getAccessToken(function (token) {
    // ..
})

Also, if you pass json: true in request options, it'll pass you json data in response

iyerrama29
  • 496
  • 5
  • 15
0

Solution provided by iyerrama29 is fine. But you can use Promise also here. Check below link on how to use Promise here.

Node.js promise request return

Pavan
  • 56
  • 3