簡體   English   中英

在帶有 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 后端(基於 express.js 的 nest.js)。 前端客戶端向后端發起請求時,如何獲取訪問后端用戶的IP地址?

我檢查了這個問題並嘗試了解決方案

使用單獨的客戶端和服務器應用程序,如何在帶有 Koa 的節點中獲取用戶的 IP 地址?

Express.js:如何獲取遠程客戶端地址

但我得到前端的服務器 IP 而不是客戶端 IP。

有沒有辦法在前端應用程序沒有任何變化的情況下,在 nest.js 中獲得真正的客戶端 IP?

根據 NestJS 文檔,有一個裝飾器可用於獲取請求 Ip 地址。 它是這樣使用的:

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

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

這是可以使用的裝飾器的完整列表: https://docs.nestjs.com/custom-decorators

您可以從Request object 中提取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();
    }
}

您可以安裝一個名為request-ip的庫:

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

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

app.use(requestIp.mw());

現在您可以從請求 object 訪問 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);
});

你可以使用 controller 中的裝飾器:

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

檢查github中的以下問題

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM