如何从控制器内确定给定请求的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
})
当前回答
我使用这个ipv4格式
req.connection.remoteAddress.split(':').slice(-1)[0]
其他回答
你可以保持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文件中的高级选项。
在节点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;
这里有很多很棒的观点,但没有一个是全面的,所以这里是我最终使用的:
function getIP(req) {
// req.connection is deprecated
const conRemoteAddress = req.connection?.remoteAddress
// req.socket is said to replace req.connection
const sockRemoteAddress = req.socket?.remoteAddress
// some platforms use x-real-ip
const xRealIP = req.headers['x-real-ip']
// most proxies use x-forwarded-for
const xForwardedForIP = (() => {
const xForwardedFor = req.headers['x-forwarded-for']
if (xForwardedFor) {
// The x-forwarded-for header can contain a comma-separated list of
// IP's. Further, some are comma separated with spaces, so whitespace is trimmed.
const ips = xForwardedFor.split(',').map(ip => ip.trim())
return ips[0]
}
})()
// prefer x-forwarded-for and fallback to the others
return xForwardedForIP || xRealIP || sockRemoteAddress || conRemoteAddress
}
我在nginx后面使用express和
req.headers.origin
对我有用吗
我使用这个ipv4格式
req.connection.remoteAddress.split(':').slice(-1)[0]