Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 704
Andre Baltieri Avatar asked Aug 18 '18 04:08

Andre Baltieri


People also ask

What is a nestjs interceptor?

A NestJS Interceptor is basically a class annotated with the @Injectable () decorator. If you wish to know more about @Injectable () decorator, please refer to the detailed post on NestJS Providers. However, apart from the decorator, an interceptor should also implement the NestInterceptor interface.

How to get the body values from the post method in nestjs?

To get the body values from the POST method request, you can use the @Body () decorator function from the @nestjs/common module in Nestjs.

How to bind a logginginterceptor in nestjs?

We can bind interceptors on various levels such as method, controller or even global. To bind an interceptor, we use the @UseInterceptor () decorator. Basically, the LoggingInterceptor will be applicable to this route handler in the controller. If you wish to know more about controllers, refer to the detailed post about NestJS Controllers.

How do I parse a route in nestjs?

We need to tell NestJS to parse the specified routes with the raw body parser. Then parse every other route with the regular JSON parser. Then you can add any middleware you like after that. Now in the controller for handling the specified route we can access the parsedRawBody parameter.


1 Answers

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) => {
like image 117
Kim Kern Avatar answered Oct 06 '22 18:10

Kim Kern