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;
————————————————
版权声明:本文为 田园幻想乡 的原创文章,遵循 CC 4.0 BY-NC-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接: http://truraly.fun/学习笔记/nodejs/express获取用户真实IP.html


本页近半年访问量: 查询中……

发布时间:

最后更新时间:

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