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

express-graphql中Context返回函数问题:鉴权逻辑异常排查

问题分析与解决方案

你的核心问题是在express-graphql中配置的context函数未被正确执行,导致鉴权中间件拿到的是函数本身([Function: context])而非预期的上下文对象。

原因说明

express-graphql确实支持将context设为函数,它会在请求处理阶段自动调用该函数并传入请求对象,返回值作为上下文传递给 resolver 和中间件。但你的代码中,context函数是嵌套在async类型的graphqlHTTP回调里返回的,部分版本的express-graphql可能存在兼容问题,导致该函数未被自动触发执行,直接将函数本身传递给了下游中间件。

修复方案

方案1:提前计算上下文对象,直接返回

把上下文的计算逻辑移到graphqlHTTP的回调中,直接返回对象而非函数,确保中间件能拿到现成的上下文:

app.use(
  "/graphql",
  graphqlHTTP(async (req: any) => {
    // 提前计算上下文内容
    const user = users.find((user) => user.username === "test user");
    const context = !user 
      ? { message: "Incorrect username or password." }
      : { user: "test user", active: "Yes", currentUser: "test user" }; // 补充中间件需要的currentUser字段

    return {
      schema: schema,
      graphiql: true,
      context: context,
    };
  })
);

方案2:显式执行context函数(保留函数形式)

如果想继续使用函数形式定义上下文,可以在graphqlHTTP回调中显式调用该函数并传入请求对象,将结果作为上下文返回:

app.use(
  "/graphql",
  graphqlHTTP(async (req: any) => {
    const getContext = (req: any) => {
      const user = users.find((user) => user.username === "test user");
      if (!user) {
        return { message: "Incorrect username or password." };
      }
      return { user: "test user", active: "Yes", currentUser: "test user" };
    };

    return {
      schema: schema,
      graphiql: true,
      context: getContext(req), // 主动执行函数获取上下文对象
    };
  })
);

额外注意事项

你的isAuthenticated中间件检查的是context.currentUser,但原context函数返回的是user字段——即使上下文正常传递,也会触发未授权错误。需要在上下文中补充currentUser字段(如上述代码所示),或者将中间件的检查逻辑改为context.user。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:15:53