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

Express自定义req字段无法传入GraphQL上下文,Resolver取值为undefined

Express + GraphQL 上下文传递失效问题解决

问题描述

在Express的Auth中间件中已成功为req对象添加isAuth和userId属性,但通过graphql-http的上下文传递到Resolver时,这两个属性始终为undefined,导致Resolver无法获取认证状态。

原因分析

  1. graphql-http的Context参数结构错误:createHandler的context函数接收的不是原生Express Request对象,而是graphql-http封装的请求上下文,原生请求对象需要从ctx.raw.req中获取。
  2. Resolver参数结构错误:GraphQL Resolver的标准参数顺序是(parent, args, context, info),而非将context包含在args对象中。

解决步骤

1. 修正GraphQL上下文的获取逻辑

修改app.ts中createHandler的context配置,从封装的上下文里取出原生Express请求对象:

// app.ts
app.use(
  '/graphql',
  createHandler({
    schema: yourSchema,
    rootValue: yourResolvers,
    context: (ctx) => ({
      isAuth: ctx.raw.req.isAuth,
      userId: ctx.raw.req.userId
    })
  })
);

2. 修正Resolver的参数结构

调整Resolver的参数顺序,正确获取上下文对象:

// Resolver
const resolvers = {
  createPost: async (parent, args, context, info) => {
    console.log('Context:', context);
    if (!context.isAuth) {
      throw new Error('未认证');
    }
    // ... 剩余业务逻辑
  }
};

3. 确保类型定义生效(可选)

如果使用TypeScript,需确保express.d.ts被TypeScript正确识别:

  • 确认tsconfig.json中include数组包含该类型文件,例如:
{
  "include": ["src/**/*", "types/**/*"]
}

内容的提问来源于stack exchange,提问作者Mr.Unforgettable

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 16:40:01