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

时间:2018-08-18 04:11:06

标签: javascript node.js nestjs

在进入控制器之前,我需要在拦截器上获取请求正文:

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 个答案:

答案 0 :(得分:2)

在拦截器中,您可以执行以下操作:

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) => {

答案 1 :(得分:0)

如果您的 interceptor 用于休息端点,我认为 Kim Kern completely covered this part in his answer

还有使用 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)
相关问题