简体   繁体   中英

NestJs - How to get request body on interceptors

I need to get the request body on my interceptor, before it goes to my controller:

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
    }
}

In your interceptor you can do:

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

Alternatively, you can use middleware where you directly have access to the request:

(req, res, next) => {

If your interceptor is for rest endpoints I think Kim Kern completely covered this part in his answer .

There are additional possibilities to use interceptor and controllers . For example controller can be an entry point for your micro service for example listening a kafka messages (or any different ones):

@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)}`);
  }
}

In this case to get body, or better to say message you need a little modification:

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

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

So to avoid of misunderstanding you can verify your request to figureOut what the value contains your payload:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM