在 NestJS 中,ExecutionContext
是一个包含了请求详细信息的对象,比如请求对象、响应对象、当前处理的控制器类和方法等。通常情况下,ExecutionContext
主要在守卫(Guards)、拦截器(Interceptors)和异常过滤器(Exception filters)中使用。然而,与中间件相比,ExecutionContext
是针对 NestJS 的上下文,而中间件则是在更底层的 Express 或者 Fastify 框架上下文中执行的。
中间件中并不能直接获取到 ExecutionContext
,因为中间件是在路由处理之前执行的,这时 NestJS 的上下文还没有完全构建。但你可以通过中间件的参数来获取到原生的请求(Request)和响应(Response)对象。
如果你需要在中间件中获取类似 ExecutionContext
中的部分信息,你可以直接访问请求对象。以下是一个 Express 中间件获取请求对象示例:
typescriptimport { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class CustomMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { // 这里你可以访问到请求对象 console.log(req.path); console.log(req.method); // 无法直接获取ExecutionContext,但可以获取原生的请求和响应对象 // 比如,获取请求头中的特定属性 const customHeader = req.headers['x-custom-header']; // 你可以在这里根据请求对象执行自定义逻辑 // ... // 然后调用 next() 继续处理流程 next(); } }
如果你确实需要在中间件中访问到 ExecutionContext
或者其他 NestJS 的上下文特有的信息,你可以考虑将中间件转换为拦截器。拦截器是在路由处理程序上下文中执行的,这样你就可以直接访问 ExecutionContext
并利用其提供的方法和属性。
以下是一个拦截器的示例:
typescriptimport { 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); // 在拦截器中可以通过 ExecutionContext 获取更多的上下文信息 return next.handle(); } }
通过这个拦截器,你就可以在执行具体的控制器方法前后,执行你需要的自定义逻辑,并且可以访问 ExecutionContext
。
2024年6月29日 12:07 回复