NestJs - 如何在拦截器上获取请求正文

NestJs - How to get request body on interceptors

我需要在我的拦截器上获取请求主体,然后再转到我的控制器:

import { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class ExcludeNullInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
        // How can I get the request body here?
        // Need to be BEFORE the Controller exec
    }
}

在你的拦截器中你可以做:

async intercept(context: ExecutionContext, stream$: Observable<any>): Observable<any> {
    const body = context.switchToHttp().getRequest().body;
    // e.g. throw an exception if property is missing

或者,您可以使用直接访问请求的中间件:

(req, res, next) => {

如果您的 interceptor 用于休息端点,我认为

还有其他使用 interceptorcontrollers 的可能性。 例如 controller 可以是您的微服务的入口点,例如收听 kafka 消息(或任何不同的消息):

@Controller()
export class DemoConsumerController {
  private readonly logger = new Logger(DemoConsumerController.name);

  @UseInterceptors(LogInterceptor)
  @EventPattern('demo-topic')
  async listenToKafkaMessage (
    @Payload() payload,
    @Ctx() context: KafkaContext,
  ) {
    this.logger.debug(`payload: ${payload}`)
    this.logger.verbose(`Topic: ${context.getTopic()}`);
    this.logger.verbose(`KafkaContext: ${JSON.stringify(context)}`);
  }
}

在这种情况下,要获取正文,或者更好地说消息,您需要稍作修改:

    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        const value = context.switchToHttp().getRequest().value

        // default rest part of code
        return next.handle()
    }

因此,为避免误解,您可以验证您的请求以找出包含您的有效负载的值:

console.log('getRequest: ', context.switchToHttp().getRequest())
// or 
console.log('context: ', context)