简体   繁体   中英

Defined variable getting changed in node.js

I am facing a wierd issue. I define a variable in my code, use it to make a call and then leave it like that. When I am trying to use it again, later, the variable is changed - probably serialized. How can I get it back in the original form?

Here is my code.

const restler = require('restler');

var baas_host = 'hostname';
var baas_app = 'appname';
var access_options = {
  data: {
    grant_type: 'client_credentials',
    client_id: 'id',
    client_secret: 'secret'
  }
}

// Get an access_token
var access_token;
getAccessToken(function (data_token) {
  access_token = data_token;
});

function getAccessToken(cb) {
  //****Here is where I see different results****//
  console.log("access_options::", access_options); 

  restler.post(baas_host+'/'+baas_app+'/token', access_options).on('complete', function (data, response) {
      cb(data.access_token);
  });
};

// Refresh if access token expired
function refreshAccessToken() {
  console.log("refreshAccessToken called.");
  // Call getAccessToken again
  getAccessToken(function (data_token) {
    access_token = data_token;
  });
}

When I am trying to reuse access_options in the refreshAccessToken() call again, later, here is what I see being printed in the second iteration as the value of access_options

{ data: <Buffer 67 72 61 6e 74  ... >,
  method: 'POST',
  parser:
   { [Function: auto]
     matchers:
      { 'application/json': [Function: json],
        'application/yaml': [Function],
        'application/xml': [Object] } },
  followRedirects: true }

Please help me understand what's happening behind the scenes?

you declare access_token as a module variable and by making this every request change it. you need to put him in a function scope so he will be "private" for the request

The only thing that comes to my mind is that the restler library is modifying your object. Try to create a new object with the information you need just before the restler.post. Something like an access_options_temp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM