如何从控制器内确定给定请求的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
})
当前回答
如果您使用的是快速版3。X或更大,您可以使用信任代理设置(http://expressjs.com/api.html#trust.proxy.options.table),它将遍历X -forward -for报头中的地址链,并将链中尚未配置为受信任代理的最新IP放入req对象的IP属性中。
其他回答
你可以像这样快速获取用户Ip
req.ip
在这个例子中,我们获取了用户的Ip,然后用req.ip把它发回给用户
app.get('/', (req, res)=> {
res.send({ ip : req.ip})
})
请求。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.
如果使用express…
req.ip
我在查这个,然后我想,等等,我用的是快递。咄。
在nodejs中简单获取远程ip:
var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
警告:
不要盲目地将其用于重要的速率限制:
let ip = request.headers['x-forwarded-for'].split(',')[0];
这很容易被欺骗:
curl --header "X-Forwarded-For: 1.2.3.4" "https://example.com"
在这种情况下,用户的真实IP地址将是:
let ip = request.headers['x-forwarded-for'].split(',')[1];
我很惊讶,没有其他答案提到这一点。