slowtokyo slowtokyo - 2 months ago 6
Javascript Question

Variable becomes undefined inside node function

I'm new to node and having trouble with a simple function. Essentially the function accepts an entity name (ownerEntity) and looks up that entity's url and port number to serve a GET request.

However, when calling the function, it throws an error:

TypeError: Cannot read property 'URL' of undefined


The function is as follows:

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;
};


The lookup hits an entry point
index.js
file in a folder called
config
that looks like the following:

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,
},
},
};


For testing I put three console logs in. The
console.log
s return the following so I can see that the
ownerEntity
variable is getting through initially, that the DATA_SERVER arguments come back, but somehow
ownerEntity
becomes undefined when looking up the 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


Any help would be greatly appreciated.

Answer

You mean:

config.DATA_SERVER[ownerEntity]

And therefore

const url = config.DATA_SERVER[ownerEntity].URL;
const port = config.DATA_SERVER[ownerEntity].PORT;

Use bracket notation for dynamic property names (like those provided by variables and such).