从模块连接时,NestJS 类或功能中间件不会运行。它也不适用于单个路径、 Controller 或每个路径。从 main.ts 连接功能中间件可以正常工作。
//main.ts
import { ValidationPipe } from '@nestjs/common'
import { NestFactory } from '@nestjs/core'
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'
import { AppModule } from './app.module'
declare const module: any
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter())
app.useGlobalPipes(new ValidationPipe())
await app.listen(2100)
if (module.hot) {
module.hot.accept()
module.hot.dispose(() => app.close())
}
}
bootstrap()
//app.module.ts
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'
import { AuthMiddleware } from './middleware/auth.middleware'
import { UserModule } from './user/user.module'
@Module({
imports: [UserModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(AuthMiddleware)
.forRoutes('(.*)')
}
}
//auth.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common'
import { FastifyRequest, FastifyReply } from 'fastify'
@Injectable()
export class AuthMiddleware implements NestMiddleware {
use(req: FastifyRequest, res: FastifyReply, next: () => void) {
console.log('test auth middleware')
next()
}
}
预期输出:测试身份验证中间件实际:无
最佳答案
问题是安装“fastify”包和“@nestjs/platform-fastify”。另外,如果你删除了“fastify”包,那么“@nestjs/platform-fastify”包中使用的依赖也会被删除,所以它不能正常工作。如果你已经安装了这两个包,卸载“fastify”并重新安装“@nestjs/platform-fastify”。
关于javascript - NestJS 中间件未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63978181/