express 获取用户真实 IP

33 阅读1分钟

来自🥬🐶程序员 Truraly | 田园 的博客,最新文章首发于:田园幻想乡 | 原文链接 | github (欢迎关注)


将用户 IP 放到 res.locals 中,方便后续中间件和路由使用。

// storeRealIP.ts
import { Request, Response, NextFunction } from "express";

function getRealIP(req: Request): string | undefined {
  // X-Forwarded-For header may contain a comma-separated list of IP addresses
  const xForwardedFor = req.headers["x-forwarded-for"] as string | undefined;

  if (xForwardedFor) {
    const ips = xForwardedFor.split(",");
    // The client's IP address is the first one in the list
    return ips[0].trim();
  }

  // If X-Forwarded-For header is not present, fall back to req.connection.remoteAddress
  return req.connection.remoteAddress;
}

function storeRealIP(req: Request, res: Response, next: NextFunction): void {
  const realIP = getRealIP(req);

  // Add the realIP to res.locals for easy access in subsequent middleware and routes
  res.locals.realIP = realIP;

  next();
}

export default storeRealIP;

————————————————

版权声明:本文为 田园幻想乡 的原创文章,遵循 CC 4.0 BY-NA-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:truraly.fun/学习笔记/nodejs…