简体   繁体   English

如何在 Node.js 中使用“x-forwarded-for”(如果可能,不使用 Express)

[英]How to use "x-forwarded-for" in Node.js (without Express if possible)

For my current project, I need to get the remote IP address in a Node.js http.createServer((req,res)=>{});对于我当前的项目,我需要在 Node.js http.createServer((req,res)=>{}) 中获取远程 IP 地址; function. function。 I've tried looking through the API documentation for Node.js itself, with no luck, then turning to Google, with most answers appearing to use Express.js.我尝试查看 Node.js 本身的 API 文档,但没有运气,然后转向谷歌,大多数答案似乎使用 Express.js。 The answers seemed to point at req.connection.remoteAddress (which works, but breaks if used with a proxy) or req.headers['x-forwarded-for'], however this returned undefined when I tried to use it.答案似乎指向 req.connection.remoteAddress (有效,但如果与代理一起使用会中断)或 req.headers['x-forwarded-for'],但是当我尝试使用它时返回未定义。 Any help is greatly appreciated.任何帮助是极大的赞赏。

You almost had it, try:您几乎拥有它,请尝试:

var clientip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

This will set clientip to the correct value if a proxy is used.如果使用代理,这会将clientip设置为正确的值。 If no proxy is used, clientip gets set to the ip address of the client initiating the connection.如果没有使用代理, clientip将设置为发起连接的客户端的 ip 地址。

'connection' is deprecated. “连接”已弃用。 since v13.0.0 - Use socket instead.v13.0.0 开始- 改用套接字。

const clientip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;

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

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