You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS中ClsModule初始化异常,无法正常使用ClsService求助

NestJS中ClsModule初始化失败问题

我在NestJS应用中尝试使用ClsModule,目的是在HTTP请求生命周期内获取请求头中的值,但该模块始终无法正确初始化。

我的应用模块代码如下:

@Module({ 
    imports: [
        ClsModule.forRoot({
            middleware: { 
                mount: true,
                setup: (cls, req: Request, res: Response) => {
                    cls.set('userId', req.headers[HttpHeaders.UserId])
                },
            },
        }),
        ConfigModule.forRoot(),
        EventModule,
    ],
    controllers: [AppController],
    providers: [
        {
            provide: APP_GUARD,
            useFactory: async (moduleRef: ModuleRef) => {
                const reflector = moduleRef.get(Reflector)
                const configService = moduleRef.get(ConfigService)
                return new AuthGuard(reflector, configService)
            },
            inject: [ModuleRef],
        },
        Reflector,
        ConfigService,
    ],
})
export class AppModule implements NestModule {
    configure(consumer: MiddlewareConsumer): void {
        consumer.apply(RequestMiddleware).forRoutes('*')
    }
}

问题出在ClsModule内部的这行代码:options = this.moduleRef.get(cls_constants_1.CLS_MIDDLEWARE_OPTIONS);,运行时发现this.moduleRef是undefined,因为该模块的构造函数从未被调用。

我单独创建的NestJS示例项目中,ClsModule的构造函数能正常执行,模块工作完全正常,初始化时还能看到日志:

DEBUG [ClsModule] Mounting ClsMiddleware to *

我已经尝试移除了应用中所有其他模块、中间件等,尽可能贴近示例项目的配置,但调用ClsService时仍然失败,打印ClsService的结果如下:

cls: ClsService {
    als: AsyncLocalStorage {
        kResourceStore: Symbol(kResourceStore),
        enabled: false,
        _onPropagate: null
    }
}

内容的提问来源于stack exchange,提问作者Atium Addict

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 02:42:52