How do I store the DB auth token so it is available to other modules in Node.js?

223 views Asked by At

I am trying to connect Node application with DataStax - Cassandra online DB drivers with the methods provided by them using the Request module of NodeJs.

Code-behind is as per below:

const request = require('request-promise');
var jar = request.jar();

var saveAuthToken;
var auth_token;
/* Fetch auth token from Datastax */

const options = {
  method: 'POST',
  url: 'https:/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-us-east1.apps.astra.datastax.com/api/rest/v1/auth',
  headers: {
      accept: '*/*', 'content-type': 'application/json','X-Cassandra-Request-Id' : '2XXXXXXX0-dc89-47e2-XXXX-84aXXXXXXXXXXXX9'
    },
  body:{username: 'database_username', password: 'database_password'},
  json:true
};
  

function callback(error,response,body){
  if (error) throw new Error(error);
  saveAuthToken =  JSON.stringify(body.authToken)
  console.log(saveAuthToken)
}

request(options,callback)

The console log gave the following output:

"dxxxxc71-xxxx-xxxx-xxxx-4xxxxxxxd"

which is supposed to be passed as a header to the next every request I make to interact with DataStax, to modify or create tables or rows.

The problem is the stored variable saveAuthToken is only available through that module only, I cannot access that variable value in another node modules, even after exporting the variable.

What have I done so far:

request(options,callback)
.then(function(){
 console.log('db-auth',saveAuthToken)
  module.exports = auth_token;

  })
 .catch(function(err){
  console.log('error',err)
 })

an export variable gives me full request payload in my other module, rather than just an auth token.

I have also tried using the request.jar() method and setting a cookie into it. but was unable to get value in my other module.

Any heads up will be appreciated. Thanks in advance

0

There are 0 answers