問題:
? ? ? ? 如題
參考:
????????nodejs+nginx獲取真實(shí)ip-騰訊云開發(fā)者社區(qū)-騰訊云
????????「轉(zhuǎn)」從限流談到偽造 IP nginx remote_addr
? ? ? ??
解決辦法:
1.設(shè)置nginx
? ? ? ? 對(duì)于代理部分,對(duì)http header添加Host、X-Real-IP、X-Forwarded-For(最重要)
????????
location /api {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:5000;
proxy_redirect off;
}
2.nestjs使用express,啟用trust proxy
? ? ? ? 需要注意,await NestFactory.create<NestExpressApplication>(AppModule);
????????需要明確使用NestExpressApplication,雖然nestjs默認(rèn)express,但是為了調(diào)用app.set('trust proxy', true),必須顯示聲明。文章來源:http://www.zghlxwxcb.cn/news/detail-647945.html
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
async function bootstrap() {
const app: NestExpressApplication = await NestFactory.create<NestExpressApplication>(AppModule);
app.set('trust proxy', true) //此接口NestExpressApplication才有
app.use(new HttpRequestMiddleware().use);
await app.listen(3000);
}
bootstrap().then();
3.可以在Request.ip中獲取到值了文章來源地址http://www.zghlxwxcb.cn/news/detail-647945.html
/**
* 自定義請(qǐng)求信息日志記錄中間件
*/
import { NextFunction, Request, Response } from 'express';
import { NestMiddleware } from '@nestjs/common';
export class HttpRequestMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
next();
// 組裝日志信息
const logFormat = {
httpType: 'Request',
ip: req.ip.split(':').pop(),
reqUrl: `${req.headers.host}${req.originalUrl}`,
reqMethod: req.method,
httpCode: res.statusCode,
params: req.params,
query: req.query,
body: req.body,
};
console.log(JSON.stringify(logFormat));
}
}
到了這里,關(guān)于nestjs:nginx反向代理服務(wù)器后如何獲取請(qǐng)求的ip地址的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!