乐闻世界logo
搜索文章和话题

NestJs - How to get request body on interceptors

1个答案

1

In NestJS, interceptors provide a powerful mechanism for intercepting and handling incoming and outgoing requests and responses. To access request content within interceptors, you must access the current execution context, which can be achieved by implementing the Interceptor interface and utilizing the ExecutionContext class.

Below are the steps to access request content in interceptors:

  1. Create an interceptor: First, create a new interceptor by applying the @Injectable decorator and implementing the NestInterceptor interface.

  2. Implement the intercept method: The NestInterceptor interface mandates implementing an intercept method that accepts two parameters: ExecutionContext and CallHandler.

  3. Access the request object from ExecutionContext: The ExecutionContext object enables access to request and response objects. You can retrieve the current HTTP request object using the switchToHttp method.

  4. Read request content: Once you have the request object, you can access its content through properties such as body, query, and params.

Here is a simple example demonstrating how to access request content in a NestJS interceptor:

typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; @Injectable() export class LoggingInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { const request = context.switchToHttp().getRequest(); const body = request.body; // Access request body const query = request.query; // Access query parameters const params = request.params; // Access route parameters console.log(`Incoming Request: ${request.method} ${request.url}`); console.log('Body:', body); console.log('Query:', query); console.log('Params:', params); // Proceed with request processing return next .handle() .pipe( tap(() => console.log(`Outgoing Response: The response has been sent.`)), ); } }

In this example, the LoggingInterceptor interceptor retrieves the current HTTP request via ExecutionContext, logs the request method, URL, body, query parameters, and route parameters. It then allows the request to continue processing with next.handle() and logs a message after the response is sent.

To integrate this interceptor into your NestJS application, register it in the module's providers array and activate it on controllers or specific routes using the @UseInterceptors decorator.

2024年6月29日 12:07 回复

你的答案