I am learning Node.js. While creating a web site, I will run the web site locally (on localhost
). When it is deployed, it will run on other servers. My question is, how do I determine if a request is from localhost or not in Node? In ASP.NET, I could use Request.IsLocal
. I'm trying to figure out how to do that in Node.
Thank you!
I am learning Node.js. While creating a web site, I will run the web site locally (on localhost
). When it is deployed, it will run on other servers. My question is, how do I determine if a request is from localhost or not in Node? In ASP.NET, I could use Request.IsLocal
. I'm trying to figure out how to do that in Node.
Thank you!
Share Improve this question asked Jan 25, 2015 at 13:04 JQuery MobileJQuery Mobile 6,30124 gold badges88 silver badges138 bronze badges1 Answer
Reset to default 4There's server.address()
to get the server address.
And request
has connection
and socket
objects, as both might hold remote address (in a remoteAddress
property) depending on a type of current connection.
But if the server is behind a reverse proxy, you'll have to pull it from appropriate header, most likely x-forwarded-for
. However I'm not sure if that holds if proxies are chained.
So, to conclude, you'd do something along the lines of:
function cliAddress(req) {
return req.connection.remoteAddress || req.socket.remoteAddress || req.headers['x-forwarded-for'];
}
server.isLocal = function(request) {
return server.address() === cliAddress(req);
}
And if you use express.js see Express.js Req.IP API.