如何从控制器内确定给定请求的IP地址?例如(在快递中):
app.post('/get/ip/address', function (req, res) {
// need access to IP address here
})
如何从控制器内确定给定请求的IP地址?例如(在快递中):
app.post('/get/ip/address', function (req, res) {
// need access to IP address here
})
当前回答
对于我使用kubernetes ingress (NGINX):
req.headers['x-original-forwarded-for']
在Node.js中非常有效
其他回答
你可以保持DRY,只使用支持IPv4和IPv6的node-ipware。
安装:
npm install ipware
在你的app.js或中间件中:
var getIP = require('ipware')().get_ip;
app.use(function(req, res, next) {
var ipInfo = getIP(req);
console.log(ipInfo);
// { clientIp: '127.0.0.1', clientIpRoutable: false }
next();
});
它将尽最大努力获取用户的IP地址或返回127.0.0.1,以表明它无法确定用户的IP地址。查看README文件中的高级选项。
在nodejs中简单获取远程ip:
var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
要求的事情。连接已弃用node@12.12.0。使用req.connection.remoteAddress获取客户端IP可能仍然有效,但不建议使用。
幸运的是,req.socket.remoteAddress自node@0.5.10以来一直存在,是一个完美的替代品:
远程IP地址的字符串表示形式。例如,'74.125.127.100'或'2001:4860:a005::68'。如果套接字被销毁(例如,如果客户端断开连接),值可能是未定义的。
请求。headers['x-forwarded-for'] || request.connection.remoteAddress . headers['x-forwarded-for'
如果有x-forward -for报头,则使用它,否则使用. remoteaddress属性。
The x-forwarded-for header is added to requests that pass through load balancers (or other types of proxy) set up for HTTP or HTTPS (it's also possible to add this header to requests when balancing at a TCP level using proxy protocol). This is because the request.connection.remoteAddress the property will contain the private IP address of the load balancer rather than the public IP address of the client. By using an OR statement, in the order above, you check for the existence of an x-forwarded-for header and use it if it exists otherwise use the request.connection.remoteAddress.
如果你正在使用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 }