admin管理员组文章数量:1355670
For my current project, I need to get the remote IP address in a Node.js http.createServer((req,res)=>{}); 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. 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. Any help is greatly appreciated.
For my current project, I need to get the remote IP address in a Node.js http.createServer((req,res)=>{}); 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. 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. Any help is greatly appreciated.
Share Improve this question asked Dec 15, 2019 at 5:39 LostEth0LostEth0 1442 silver badges11 bronze badges2 Answers
Reset to default 7You 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. If no proxy is used, clientip
gets set to the ip address of the client initiating the connection.
'connection' is deprecated. since v13.0.0 - Use socket instead.
const clientip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
本文标签: javascriptHow to use quotxforwardedforquot in Nodejs (without Express if possible)Stack Overflow
版权声明:本文标题:javascript - How to use "x-forwarded-for" in Node.js (without Express if possible) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744019962a2577035.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论