如何从控制器内确定给定请求的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})
    
})

其他回答

var ip = req.headers['x-forwarded-for'] ||
     req.socket.remoteAddress ||
     null;

请注意,有时您可以在req.headers['x-forwarded-for']中获得多个IP地址。此外,并不总是设置x-forward -for报头,这可能会抛出错误。

该字段的一般格式为:

x-forward -for: client, proxy1, proxy2, proxy3

其中的值是一个逗号+空格分隔的IP地址列表,最左边是原始客户端,每个传递请求的后续代理添加接收请求的IP地址。在本例中,请求通过proxy1、proxy2和proxy3传递。Proxy3显示为请求的远程地址。

这是Arnav Gupta提出的解决方案,Martin在下面的评论中为未设置x-forward -for的情况提出了修复建议:

var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim() || 
         req.socket.remoteAddress

使用现代JS的建议:

仅在设置时处理x-forward -for,如果设置了,则取第一个地址 其他参数使用可选链接(?.)

const parseIp = (req) =>
    req.headers['x-forwarded-for']?.split(',').shift()
    || req.socket?.remoteAddress

console.log(parseIp(req))
// => 127.0.0.1

如果你有多个ip,这对我来说是可行的:

Var ipaddress = (req。标题(“x-forwarded-for”)| | req.connection.remoteAddress | | req.socket.remoteAddress | | req.connection.socket.remoteAddress) .split (", ") [0];

Var ipaddress = (req。标题(“x-forwarded-for”)| | req.connection.remoteAddress | | req.socket.remoteAddress | | req.connection.socket.remoteAddress) .split (", ") [0];

在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.