在带有 Nest.js 的 Node 中,如何在单独的客户端和服务器应用程序中获取用户的 IP 地址

how to I get a user's IP address when separate client and server apps, in Node with Nest.js

我有两个应用程序,一个是前端 (react.js),另一个是 REST API 后端(nest.js 基于 express.js)。前端客户端向后端发起请求时,如何获取访问后端的用户IP地址?

我检查了这个问题并尝试了解决方案

Express.js: how to get remote client address

但我得到的是前端的服务器 IP 而不是客户端 IP。

有没有办法在前端应用程序不做任何更改的情况下,在nest.js中获得真实的客户端IP?

您可以安装名为 request-ip 的库:​​

npm i --save request-ip
npm i --save-dev @types/request-ip

main.ts 文件中,在您的应用程序中注入 request-ip 中间件:

app.use(requestIp.mw());

现在您可以从请求对象访问 clientIp:

req.clientIp

另一种方法是定义装饰器:

import { createParamDecorator } from '@nestjs/common';
import * as requestIp from 'request-ip';

export const IpAddress = createParamDecorator((data, req) => {
    if (req.clientIp) return req.clientIp;
    return requestIp.getClientIp(req);
});

并且您可以在控制器中使用装饰器:

@Get('/users')
async users(@IpAddress() ipAddress){
}

检查 github 中的以下 issue

如果您可以使用第 3 方库。你可以查看request-ip

https://github.com/pbojinov/request-ip

您可以从 Request 对象中提取 IP 地址

我将它用作在日志条目中打印用户 IP 地址的中间件,我是这样做的:

import { Injectable, Logger, NestMiddleware } from "@nestjs/common";
import { NextFunction, Request, Response } from "express";

@Injectable()
export class HttpLoggerMiddleware implements NestMiddleware {
    private logger = new Logger();

    use(request: Request, response: Response, next: NextFunction): void {
        const { ip, method, originalUrl } = request;

        response.on("finish", () => {
            const msg = `${ip} ${method} ${originalUrl}`;
            this.logger.log(msg);
        });

        next();
    }
}

根据 NestJS 文档,有一个装饰器可用于获取请求的 IP 地址。它是这样使用的:

import {Get, Ip} from "@nestjs/common"

@Get('myEndpoint')
async myEndpointFunc(@Ip() ip){
console.log(ip)
}

以下是可以使用的装饰器的完整列表: https://docs.nestjs.com/custom-decorators