You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nest.js拦截器中获取GET请求的query查询参数

Nest.js拦截器获取查询参数问题解答

错误点

你调用了错误的请求属性获取参数:

  • request.params 对应路由路径参数,仅当你路由配置了路径占位符(如@Get('/data/:type'))时才有值,你当前请求没有匹配的路径参数,所以返回空对象
  • 你需要的?foo=1,2这类查询参数,全部存储在request.query属性中

正确代码实现

@Injectable()
export class MyRequestInterceptor implements NestInterceptor {
  constructor(private logger: MyLogger) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<string> {
    const http = context.switchToHttp();
    const request = http.getRequest();
    // 读取查询参数
    const query = request.query;
    // 如需同时打印路径参数、查询参数、POST请求体可使用以下写法
    // const logInfo = {params: request.params, query: request.query, body: request.body}
    this.logger.info(JSON.stringify(query)); 

    return next.handle()
  }
}

补充说明

  • 以上写法同时兼容Nest默认的Express适配器和Fastify适配器,两个框架的请求对象对query、params、body三个属性的命名是一致的
  • 如果是GraphQL场景的拦截器,需要通过GqlExecutionContext.create(context).getContext()获取请求上下文,不能用switchToHttp()

内容的提问来源于stack exchange,提问作者user842225

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:09:03