如何从控制器内确定给定请求的IP地址?例如(在快递中):

app.post('/get/ip/address', function (req, res) {
    // need access to IP address here
})

当前回答

你可以像这样快速获取用户Ip

req.ip

在这个例子中,我们获取了用户的Ip,然后用req.ip把它发回给用户

app.get('/', (req, res)=> { 
    res.send({ ip : req.ip})
    
})

其他回答

在节点10.14中,在nginx后面,你可以通过nginx头请求它来检索ip,就像这样:

proxy_set_header X-Real-IP $remote_addr;

然后在你的app.js中:

app.set('trust proxy', true);

在那之后,你想让它出现的地方:

var userIp = req.header('X-Real-IP') || req.connection.remoteAddress;

对于我使用kubernetes ingress (NGINX):

req.headers['x-original-forwarded-for']

在Node.js中非常有效

以下函数涵盖了所有的情况,将会有所帮助

var ip;
if (req.headers['x-forwarded-for']) {
    ip = req.headers['x-forwarded-for'].split(",")[0];
} else if (req.connection && req.connection.remoteAddress) {
    ip = req.connection.remoteAddress;
} else {
    ip = req.ip;
}console.log("client IP is *********************" + ip);

如果你使用express.js,

app.post('/get/ip/address', function (req, res) {
      res.send(req.ip);
})

我们可以在node js中检查这段代码

const os       = require('os');
const interfaces = os.networkInterfaces();

let addresses = [];

for (var k in interfaces) {

    for (var k2 in interfaces[k]) {

        const address = interfaces[k][k2];

        if ( (address.family === 'IPv4' || address.family === 'IPv6')  && 
            !address.internal) {

            addresses.push(address.address);

        }
    }
}
console.log(addresses);