为 express.js 应用程序而不是 req.ip 使用 request-ip 包是否值得

Is it worth it to use request-ip package for an express.js app instead of req.ip

我需要做一个基本的洪水控制,没有什么很复杂的。如果他们在短时间内请求太多次,我想获取源 IP 并延迟答复。 我看到有一个 req.ip 字段还有一个包:https://www.npmjs.com/package/request-ip

有什么区别?

我建议您使用 request-ip 模块,因为它会在请求中查找特定的 header,如果它们不存在则回退到一些默认值。

以下是它用于从请求中确定用户 ip 的顺序。

  1. X-Client-IP
  2. X-Forwarded-Forheader可能return多个IP地址,格式为:“客户端IP,代理1 IP,代理2 IP”,所以我们取第一个。
  3. X-Real-IP (nginx proxy/FastCGI)
  4. X-Cluster-Client-IP(Rackspace LB、Riverbed Stingray)
  5. #2 的排列,例如:X-ForwardedForwarded-ForForwarded
  6. req.connection.remoteAddress
  7. req.socket.remoteAddress
  8. req.connection.socket.remoteAddress
  9. req.info.remoteAddress

无论您的 Web 服务器配置或代理设置,甚至连接技术如何,它都允许获取真实的客户端 IP(HTTPẀebSocket...)

你也可以看看快递req.ips(是的,ips,不是req.ip)属性得到更多有关请求的信息:

req.ips (http://expressjs.com/en/api.html)

When the trust proxy setting does not evaluate to false, this property contains an array of IP addresses specified in the X-Forwarded-For request header. Otherwise, it contains an empty array. This header can be set by the client or by the proxy.

For example, if X-Forwarded-For is client, proxy1, proxy2, req.ips would be ["client", "proxy1", "proxy2"], where proxy2 is the furthest downstream.