[英]how to I get a user's IP address when separate client and server apps, in Node with Nest.js
I have two apps, one front end (react.js) and one a REST API back-end(nest.js based on express.js).我有两个应用程序,一个前端(react.js)和一个 REST API 后端(基于 express.js 的 nest.js)。 How do I get the IP address of the user accessing the back-end when the front-end client makes a request to the back-end?前端客户端向后端发起请求时,如何获取访问后端用户的IP地址?
I checked this question and try the solutions我检查了这个问题并尝试了解决方案
With separate client and server apps, how do I get a user's IP address, in Node with Koa? 使用单独的客户端和服务器应用程序,如何在带有 Koa 的节点中获取用户的 IP 地址?
Express.js: how to get remote client address Express.js:如何获取远程客户端地址
but I get server IP of front-end not client IP.但我得到前端的服务器 IP 而不是客户端 IP。
Is there a way without any change in front-end app, I get real client IP in nest.js?有没有办法在前端应用程序没有任何变化的情况下,在 nest.js 中获得真正的客户端 IP?
According to the NestJS docs, there's a decorator available to get the request Ip Address.根据 NestJS 文档,有一个装饰器可用于获取请求 Ip 地址。 It's used like this:它是这样使用的:
import {Get, Ip} from "@nestjs/common"
@Get('myEndpoint')
async myEndpointFunc(@Ip() ip){
console.log(ip)
}
Here's a complete list of decorators that can be used: https://docs.nestjs.com/custom-decorators这是可以使用的装饰器的完整列表: https://docs.nestjs.com/custom-decorators
You can extract IP address from a Request
object.您可以从Request
object 中提取IP 地址。
I am using it as a middleware to print user's IP address in a log entry, here is how I do that:我将它用作中间件,在日志条目中打印用户的 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();
}
}
You may install a library called request-ip
:您可以安装一个名为request-ip
的库:
npm i --save request-ip
npm i --save-dev @types/request-ip
In main.ts
file inject request-ip middleware within your app:在main.ts
文件中,在您的应用程序中注入 request-ip 中间件:
app.use(requestIp.mw());
Now you can access clientIp from request object:现在您可以从请求 object 访问 clientIp:
req.clientIp
Another way is by defining a decorator:另一种方法是定义装饰器:
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);
});
And you can use the decorator in controller:你可以使用 controller 中的装饰器:
@Get('/users')
async users(@IpAddress() ipAddress){
}
If you are fine using 3rd-party library.如果您可以使用 3rd 方库。 You can check request-ip你可以查看request-ip
https://github.com/pbojinov/request-ip https://github.com/pbojinov/request-ip
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.