NestJs - 如何在拦截器中获取请求体

13

在我的拦截器中,我需要获取请求体内容,在请求被传递到控制器之前:

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
    }
}
2个回答

21
在您的拦截器中,您可以这样做:
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) => {

0

如果你的拦截器是用于rest端点,我认为Kim Kern在他的回答中完全涵盖了这部分内容

还有其他可能性可以使用拦截器控制器。 例如,控制器可以是你的微服务的入口点,例如监听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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接