Nest.js 将变量从中间件传递到控制器

Nest.js pass variable from middleware to controller

我在 Nest.js 中找不到将变量从中间件传递到结构的明确方法。我正在我的 AuthMiddleware 中验证一个 JWT,我想让控制器可以访问这个令牌。
下面只是我的中间件的摘录,以提供代码示例。我想让 token 可以在我的控制器内部访问。

import { Request, Response, NextFunction } from 'express';
// other imports

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    const authHeader = req.header('authorization');

    if (!authHeader) {
      throw new HttpException('No auth token', HttpStatus.UNAUTHORIZED);
    }

    const bearerToken: string[] = authHeader.split(' ');
    const token: string = bearerToken[1];

    res.locals.token = token;
  }
}

我已经尝试通过更改 res.locals 变量使令牌可访问,但响应对象在我的控制器中仍然是空的。 这是我的控制器,我想在其中访问中间件的令牌:

@Controller('did')
export default class DidController {
  constructor(private readonly didService: DidService) {}

  @Get('verify')
  async verifyDid(@Response() res): Promise<string> {
    console.log(res)
    // {}
    return res;
  }
import { Request, Response, NextFunction } from 'express';
// other imports

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    const authHeader = req.header('authorization');

    if (!authHeader) {
      throw new HttpException('No auth token', HttpStatus.UNAUTHORIZED);
    }

    const bearerToken: string[] = authHeader.split(' ');
    const token: string = bearerToken[1];

    res.locals.token  = token;

    next();  ====> add this to middleware
  }
}

控制器

import { Controller, Get, Response } from '@nestjs/common';


@Controller()
export class AppController {
  constructor() {}


  @Get('verify')
  async verifyDid(@Response() res): Promise<string> {
    console.log(res.locals);
    return res;
  }
}

应用中间件

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes('*');
  }
}