如何从控制器内确定给定请求的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
})
当前回答
你可以像这样快速获取用户Ip
req.ip
在这个例子中,我们获取了用户的Ip,然后用req.ip把它发回给用户
app.get('/', (req, res)=> {
res.send({ ip : req.ip})
})
其他回答
我知道这个问题已经被回答了,但下面是我写的一个现代ES6版本,它遵循airbnb的eslint标准。
const getIpAddressFromRequest = (request) => {
let ipAddr = request.connection.remoteAddress;
if (request.headers && request.headers['x-forwarded-for']) {
[ipAddr] = request.headers['x-forwarded-for'].split(',');
}
return ipAddr;
};
X-Forwarded-For报头可以包含以逗号分隔的代理ip列表。订单是client,proxy1,proxy2,…,proxyN。在现实世界中,人们实现的代理可以在这个报头中提供他们想要的任何东西。如果你是负载均衡器之类的,你至少可以相信列表中的第一个IP至少是某个请求通过的代理。
要求的事情。连接已弃用node@12.12.0。使用req.connection.remoteAddress获取客户端IP可能仍然有效,但不建议使用。
幸运的是,req.socket.remoteAddress自node@0.5.10以来一直存在,是一个完美的替代品:
远程IP地址的字符串表示形式。例如,'74.125.127.100'或'2001:4860:a005::68'。如果套接字被销毁(例如,如果客户端断开连接),值可能是未定义的。
在节点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;
在Typescript中使用ValidatorJS。下面是NodeJS中间件:
// Extract Client IP Address
app.use((req, res, next) => {
let ipAddress = (req.headers['x-forwarded-for'] as string || '').split(',')[0]
if (!validator.isIP(ipAddress))
ipAddress = req.socket.remoteAddress?.toString().split(':').pop() || ''
if (!validator.isIP(ipAddress))
return res.status(400).json({errorMessage: 'Bad Request'})
req.headers['x-forwarded-for'] = ipAddress
next()
})
在这里,我假设所有请求都应该有一个有效的IP地址,因此如果没有找到有效的IP地址,则返回一个代码为400的响应。
请求。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.