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

NestJS : How to get ExecutionContext in Middleware

1个答案

1

In NestJS, ExecutionContext is an object containing detailed request information, such as the request object, response object, the current controller class, and method being processed. Typically, ExecutionContext is primarily used in Guards, Interceptors, and Exception filters. However, compared to middleware, ExecutionContext is specific to the NestJS context, whereas middleware operates within the lower-level Express or Fastify framework context. Middleware cannot directly access ExecutionContext as it executes before route handling, when the NestJS context has not yet been fully constructed. However, you can access the native Request and Response objects through the middleware's parameters. If you need to access parts of the information found in ExecutionContext within middleware, you can directly access the request object. The following is an example of an Express middleware accessing the request object:

typescript
import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class CustomMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { // Here you can access the request object console.log(req.path); console.log(req.method); // Cannot directly access ExecutionContext, but can access native Request and Response objects // For example, retrieve a specific property from request headers const customHeader = req.headers['x-custom-header']; // You can execute custom logic here based on the request object // ... // Then call next() to continue processing next(); } }

If you indeed need to access ExecutionContext or other NestJS-specific context information within middleware, consider converting the middleware to an interceptor. Interceptors operate within the route handler context, enabling direct access to ExecutionContext and the use of its methods and properties. The following is an example of an interceptor:

typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; @Injectable() export class CustomInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { const request = context.switchToHttp().getRequest(); console.log(request.path); console.log(request.method); // Within interceptors, you can access more context information via ExecutionContext return next.handle(); } }

With this interceptor, you can execute custom logic before and after the execution of specific controller methods, and access ExecutionContext.

2024年6月29日 12:07 回复

你的答案