我是 Node 新手,在使用一个简单的函数时遇到了麻烦。本质上,该函数接受实体名称 (ownerEntity) 并查找该实体的 url 和端口号以服务 GET 请求。
但是,调用该函数时,会抛出错误:TypeError: Cannot read property 'URL' of undefined
功能如下:
const config = require('./index.js');
module.exports = function dataServerUrl(ownerEntity) {
console.log(ownerEntity);
console.log(config.DATA_SERVER);
console.log(config.DATA_SERVER.ownerEntity);
const url = config.DATA_SERVER.ownerEntity.URL;
const port = config.DATA_SERVER.ownerEntity.PORT;
const urlParameter = url + ':' + port;
return urlParameter;
};
查找到达入口点 index.js
文件位于名为 config
的文件夹中看起来像下面这样:
module.exports = {
DATA_SERVER: {
1111: {
URL: process.env.SERVER_1_URL,
PORT: process.env.SERVER_1_PORT,
},
2222: {
URL: process.env.SERVER_2_URL,
PORT: process.env.SERVER_2_PORT,
},
3333: {
URL: process.env.SERVER_3_URL,
PORT: process.env.SERVER_3_PORT,
},
},
};
为了进行测试,我输入了三个控制台日志。console.log
返回以下内容,以便我可以看到 ownerEntity
变量最初通过,DATA_SERVER 参数返回,但不知何故 ownerEntity
查找 URL 时变为未定义。
1111
{ '1111': { URL: '0.0.0.0', PORT: '8080' },
'2222': { URL: '192.168.99.100', PORT: '8080' },
'3333': { URL: '192.168.99.100', PORT: '8081' } }
undefined
任何帮助将不胜感激。
最佳答案
你的意思是:
config.DATA_SERVER[ownerEntity]
因此
const url = config.DATA_SERVER[ownerEntity].URL;
const port = config.DATA_SERVER[ownerEntity].PORT;
对动态属性名称使用括号表示法(如变量等提供的名称)。
关于javascript - 变量在 Node 函数内变为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39737135/