如何在nest.js中为ApplicationModule以外的模块应用中间件?

时间:2018-02-24 08:15:06

标签: javascript typescript dependency-injection nestjs

我试图像这样使用基于配置的中间件:

export class UsersModule implements NestModule{
  configure(consumer: MiddlewaresConsumer): void {
    const authRoutes = UsersController.getAuthRoutes();
    consumer
      .apply(AuthMiddleware)
      .forRoutes(...authRoutes);
  }
}

方法getAuthRoutes是静态的:

  public static getAuthRoutes(){
    return [
      { path: `/api/users`, method: RequestMethod.ALL},
    ];
  }

我的AuthMIddleware非常基础:

@Middleware()
export class AuthMiddleware implements NestMiddleware {
  constructor(
    @Inject(constants.logger) private logger: Winston,
  ){}

  resolve(...args: any[]): ExpressMiddleware {
    // return passport.authenticate('jwt', { session: false });
    return (req, res, next) => {
      this.logger.debug('AuthMiddleware');
      next();
    };
  }
}

它只是在控制台中记录行。我试图通过get request / api / users访问,我获取用户列表,但在控制台中没有AuthMiddleware消息。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

查看我的问题here。它只是对文档的误解。