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

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

当前回答

如果你正在使用Graphql-Yoga,你可以使用以下函数:

const getRequestIpAddress = (request) => { const requestIpAddress = request.request。headers['X-Forwarded-For'] || request.request.connection.remoteAddress . headers['X-Forwarded-For' if (!requestIpAddress)返回null const ipv4 = new RegExp(“(?:(?:25(0 - 5)| 2[0 - 9][0 - 4]|[01]?[0 - 9][0 - 9]?)\){3}(?:25(0 - 5)| 2[0 - 9][0 - 4]|[01]?[0 - 9][0 - 9]?)”) const [ipAddress] = requesttipaddress .match(ipv4) 返回ipAddress }

其他回答

如果您使用的是快速版3。X或更大,您可以使用信任代理设置(http://expressjs.com/api.html#trust.proxy.options.table),它将遍历X -forward -for报头中的地址链,并将链中尚未配置为受信任代理的最新IP放入req对象的IP属性中。

在nodejs中简单获取远程ip:

var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;

我们可以在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);

函数getCallerIP(请求){ Var IP = request。标题(“x-forwarded-for”)| | request.connection.remoteAddress | | request.socket.remoteAddress | | request.connection.socket.remoteAddress; IP = IP .split(',')[0]; IP = IP .split(':').slice(-1);//如果IP以“::ffff:146.xxx.xxx.xxx”格式返回 返回的ip; }

我在nginx后面使用express和

req.headers.origin

对我有用吗