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

apollo-server-express的context函数间隔执行是否属于正常现象?

结论

这种情况属于正常现象,不是配置错误,触发原因和解决方案如下:

触发原因

  • 最常见的场景是你打开了Apollo Server默认开启的GraphQL Playground开发调试页面:Playground默认会每隔2秒左右发送一次自省查询请求,用来自动同步最新的Schema定义、更新字段补全提示,每一次入站的GraphQL请求都会触发context函数执行,就会产生间隔日志。
  • 如果你没有打开Playground,可能是有健康检查探针、前端定时轮询等其他定时请求访问你的GraphQL服务,同样会触发context函数执行。

验证&解决方法

  • 你可以修改context函数的代码,打印请求信息确认来源:
context: ({ event, context, express }) => {
  // 打印请求方法、路径、请求体内容确认请求类型
  console.log('context触发', express.req.method, express.req.path, express.req.body)
}

如果请求体里有query: { __schema }这类字段,就说明是Playground的自省请求,无需额外处理:

  • 开发环境属于正常调试行为,不影响业务逻辑,无需修改
  • 生产环境Apollo Server默认会关闭Playground和自省功能,这类自动请求会自动消失
  • 如果你希望开发环境也关闭这类自动请求,可以在ApolloServer配置中添加参数关闭自省和Playground:
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ event, context, express }) => {
    console.log('context')
  },
  // 添加以下两行配置
  introspection: false,
  playground: false
})

注意关闭后你将无法正常使用Playground的代码补全、Schema预览功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:15:07