简体   繁体   English

确定Node.js应用程序中的Request是否为Local

[英]Determine if Request is Local in Node.js app

I am learning Node.js. 我正在学习Node.js. While creating a web site, I will run the web site locally (on localhost ). 在创建网站时,我将在本地运行该网站(在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? 我的问题是,如何在Node中确定请求是否来自localhost? In ASP.NET, I could use Request.IsLocal . 在ASP.NET中,我可以使用Request.IsLocal I'm trying to figure out how to do that in Node. 我想弄清楚如何在Node中做到这一点。

Thank you! 谢谢!

There's server.address() to get the server address. 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. request具有connectionsocket对象,因为两者都可以保存远程地址(在remoteAddress属性中),具体取决于当前连接的类型。

But if the server is behind a reverse proxy, you'll have to pull it from appropriate header, most likely x-forwarded-for . 但是,如果服务器位于反向代理之后,则必须从适当的标头中提取它,很可能是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. 如果您使用express.js,请参阅Express.js Req.IP API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM