【发布时间】:2021-01-06 17:12:11
【问题描述】:
从模块连接时,NestJS 类或功能中间件不运行。它也不适用于单个路径、控制器或每个路径。从 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()
}
}
预期输出:测试身份验证中间件
实际:没有
【问题讨论】:
标签: javascript node.js typescript nestjs fastify