如何从控制器内确定给定请求的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
})
当前回答
Var ipaddress = (req。标题(“x-forwarded-for”)| | req.connection.remoteAddress | | req.socket.remoteAddress | | req.connection.socket.remoteAddress) .split (", ") [0];
其他回答
在节点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;
如果你正在使用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 }
在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的响应。
以下函数涵盖了所有的情况,将会有所帮助
var ip;
if (req.headers['x-forwarded-for']) {
ip = req.headers['x-forwarded-for'].split(",")[0];
} else if (req.connection && req.connection.remoteAddress) {
ip = req.connection.remoteAddress;
} else {
ip = req.ip;
}console.log("client IP is *********************" + ip);
警告:
不要盲目地将其用于重要的速率限制:
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];
我很惊讶,没有其他答案提到这一点。