I have this code as part of a nodejs application that runs behind an nginx proxy:
var ip_address = (request.headers['x-real-ip']);
if (ip_address !== "127.0.0.1") {
var ip = request.headers['x-real-ip'];
console.log(ip);
}
else {
var ip = "173.194.41.100";
console.log(ip);
}
What I am trying to achieve is that on my local dev machine, for testing i use a fixed IP address, otherwise it reads the x-real-ip from the request header.
My question, is there a way to make this more full proof, for example, is there a way to by pass this loop thus making the var ip return null, which would create a traceback on my app?
If you change it slightly, we can be sure that
ipwill not benull:Your original code would make
ipnullifrequest.headers['x-real-ip']evaluated tonull, because your condition (ip_address !== "127.0.0.1") would betrue, and you’d grabrequest.headers['x-real-ip'](null) intoip.With the modified code above, we don’t have that problem, and we’ve been able to make it a bit more concise as well.