如何在 Nestjs 中重写 url 路径?
How to rewrite url path in Nestjs?
我想重写 url 就像 '/api/example' 到 '/example'
我试过下面的代码,但它不起作用
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class RewriteApiEndpointMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
req.originalUrl = req.originalUrl.replace(/^\/api/, '');
next();
}
}
我找到了解决方案
第 1 步:
consumer
.apply(RewriteApiEndpointMiddleware)
.forRoutes('/') // <--- not the .forRoutes('*')
第 2 步:
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class RewriteApiEndpointMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
req.url = req.url.replace(/^\/api/, ''); // <--- not the .originalUrl
next();
}
}
现在它按预期工作了
我想重写 url 就像 '/api/example' 到 '/example'
我试过下面的代码,但它不起作用
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class RewriteApiEndpointMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
req.originalUrl = req.originalUrl.replace(/^\/api/, '');
next();
}
}
我找到了解决方案
第 1 步:
consumer
.apply(RewriteApiEndpointMiddleware)
.forRoutes('/') // <--- not the .forRoutes('*')
第 2 步:
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class RewriteApiEndpointMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
req.url = req.url.replace(/^\/api/, ''); // <--- not the .originalUrl
next();
}
}
现在它按预期工作了