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

如何将req请求传入Apollo Server自定义的createContext上下文生成函数

问题解决方法

问题根源

ApolloServer的context配置项要求传入请求级回调函数:每次客户端请求到来时Apollo会自动执行该函数,并将当前请求对应的上下文对象(包含req、connection等属性)作为参数注入。

你当前的写法是在ApolloServer初始化阶段就直接执行了createContext,将自定义的箭头函数(req) => req作为参数传入,所以后续所有请求拿到的ctx.request都是这个静态的函数对象,而非动态的实际请求内容。

修复方案

1. 修改server.ts的context配置

只需要将context配置为回调函数,每次请求时将Apollo注入的请求参数传给createContext即可:

import { ApolloServer } from 'apollo-server'
import { schema } from './nexusSchema'
import { createContext } from './context'

const server = new ApolloServer({
  schema,
  // 传入回调函数,由Apollo在每次请求时触发执行
  context: (requestContext) => createContext(requestContext),
})

server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`)
})

修改后你在resolver中打印ctx.request就能拿到符合你定义的Context接口结构的请求对象,包括HTTP请求的headers、订阅连接的Authorization等字段都可以正常获取。

可选优化:精简上下文参数

如果你不需要用到完整的requestContext,只需要HTTP请求对象,可以同步调整两处代码:

  • server.ts中只提取req传入:
context: ({ req }) => createContext(req)
  • 修改context.ts中的Context接口和createContext函数的入参类型,适配Express请求对象即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 12:24:06