李恒道 发表于 2023-1-6 02:54:18

nestjs passport为什么需要导入passportModule

在翻阅@nestjs/passport源码中可以搜到关键字
```
const NO_STRATEGY_ERROR = `In order to use "defaultStrategy", please, ensure to import PassportModule in each place where AuthGuard() is being used. Otherwise, passport won't work correctly.`;
```
使用defaultStrategy必须确保在每个使用AuthGuard导入PassportModule,否则passport无法正常工作
搜一下这个问题的触发位置
```js
    constructor(@Optional() options?: AuthModuleOptions) {
      this.options = options ?? this.options;
      if (!type && !this.options.defaultStrategy) {
      new Logger('AuthGuard').error(NO_STRATEGY_ERROR);
      }
    }
```
这里判断了type盒options,options如果没有传入则默认AuthModuleOptions
我们搜一下AuthModuleOptions
```js
export class PassportModule {
static register(options: IAuthModuleOptions): DynamicModule {
    return {
      module: PassportModule,
      providers: [{ provide: AuthModuleOptions, useValue: options }],
      exports:
    };
}
}
```
到这里就真相大白了,如果你没有传入type告诉用什么策略
这个时候就会尝试获取AuthModuleOptions默认策略,AuthModuleOptions来自于PassportModule 的register提供
所以如果你想使用AuthGuard不传入任何值
必须在同模块引入PassportModule
页: [1]
查看完整版本: nestjs passport为什么需要导入passportModule