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?
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 ip
will not be null
:
var ip, ip_address;
ip = ip_address = request.headers['x-real-ip'];
if (ip === null || ip === "127.0.0.1") {
ip = "173.194.41.100";
}
console.log(ip);
Your original code would make ip
null
if request.headers['x-real-ip']
evaluated to null
, because your condition (ip_address !== "127.0.0.1"
) would be true
, and you'd grab request.headers['x-real-ip']
(null
) into ip
.
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.