简体   繁体   English

Module.exports函数为变量返回“未定义”

[英]Module.exports function returning 'undefined' for variable

I have the following js file that has exports: 我有以下具有导出功能的js文件:

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'. 这两个函数都可以正常工作并成功调用,但是从getClientAuthToken返回的clientAuthToken变量为'undefined'。

When I log the auth token in the function itself, I can see that it has been set correctly. 当我将auth令牌登录到函数本身中时,可以看到它已正确设置。 What am I doing wrong here? 我在这里做错了什么? Do I need to export the variable in module.exports too? 我也需要在module.exports export变量吗?

but the clientAuthToken variable returned from the getClientAuthToken is 'undefined'. 但是从getClientAuthToken返回的clientAuthToken变量是'undefined'。

Because you are not returning anything. 因为您什么也没退。

Add return to the function getClientAuthToken : 向函数getClientAuthToken添加return

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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