Skip to content

express 获取用户真实 IP

目录


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

ts
// 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;

Copyright © 2022 田园幻想乡 浙ICP备2021038778号-1