简体   繁体   中英

Module.exports function returning 'undefined' for variable

I have the following js file that has exports:

module.exports = {
  setClientAuthToken: function(authToken) {
    setClientAuthToken(authToken);
  },
  getClientAuthToken: function() {
    getClientAuthToken();
  }
};

var clientAuthToken;

function setClientAuthToken(authToken) {
  clientAuthToken = authToken;
}

function getClientAuthToken() {
  console.log('here!!!!!!');
  console.log('auth token' + clientAuthToken);
  if (!clientAuthToken) {
    console.error("Client Auth Token has not been set");
  } else {
    return clientAuthToken;
  }
}

Both functions work and are called successfully, but the clientAuthToken variable returned from the getClientAuthToken is 'undefined'.

When I log the auth token in the function itself, I can see that it has been set correctly. What am I doing wrong here? Do I need to export the variable in module.exports too?

but the clientAuthToken variable returned from the getClientAuthToken is 'undefined'.

Because you are not returning anything.

Add return to the function getClientAuthToken :

module.exports = {
  setClientAuthToken: function(authToken) {
    setClientAuthToken(authToken);
  },
  getClientAuthToken: function() {
    return getClientAuthToken(); // <-- return
  }
};

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