如何从控制器内确定给定请求的IP地址?例如(在快递中):

app.post('/get/ip/address', function (req, res) {
    // need access to IP address here
})

当前回答

这里有很多很棒的观点,但没有一个是全面的,所以这里是我最终使用的:

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
}

其他回答

你可以使用request-ip来获取用户的ip地址。它处理了很多不同的边界情况,其中一些在其他答案中提到过。

披露:我创建了这个模块

安装:

npm install request-ip

在你的应用中:

var requestIp = require('request-ip');

// inside middleware handler
var ipMiddleware = function(req, res, next) {
    var clientIp = requestIp.getClientIp(req); // on localhost > 127.0.0.1
    next();
};

希望这能有所帮助

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的响应。

在节点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;

如果你使用express.js,

app.post('/get/ip/address', function (req, res) {
      res.send(req.ip);
})