简体   繁体   中英

How to get Real user IP or Remote IP address in Node JS Express JS

I want to ask, I have an application using expressjs now I am asked to display the ip of the user who accesses the application but it always displays the ip of the server, which wants to display the ip of the user accessing the application or the laptop accessing the application maybe someone can help me thanks in advance

If you are getting 127.0.0.1 it means you are running express behind a web server, perhaps Apache or Nginx or IIS. If so you need to understand that your users do not connect to your express application. Instead your web server connects to your express application so it is correct that the client's (web server's) ip address is 127.0.0.1.

You cannot fix this in express alone since in this case express has no direct connection to your user's machine. You need to configure your web server to forward the client's IP address to express. How you do this depends on your web server. Obviously Apache, Nginx, IIS, Lighttpd etc. all have different configuration formats.

The most common way to do this is to configure your web server to set the X-Forwarded-For header. Then in express you need to read the x-forwarded-for header in req .

Google your web server's name and "x-forwarded-for" for how to configure your server to do this.

maybe this package can help you https://www.npmjs.com/package/ext-ip

let extIP = require("ext-ip")();


extIP.get().then(ip => {
    console.log(ip);
}, err => {
    console.error(err);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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