Gatsby对接Apollo联邦网关时gatsby-source-graphql报400错误如何排查?
gatsby-source-graphql对接Apollo Federation网关400错误排查方案
第一步:获取详细报错信息
400错误通常由网关校验请求不通过返回,默认不会打印完整错误详情,可通过以下三种方式拿到具体原因:
- 执行构建时开启GraphQL调试模式,命令为
GATSBY_DEBUG=graphql yarn build,运行后终端会打印插件发送的完整请求内容、网关返回的完整响应体,可直接查看错误字段。 - 临时修改
node_modules/gatsby-source-graphql/fetch.js文件,在抛出错误前添加console.log(response)打印完整返回结果,就能看到网关返回的具体错误描述。 - 手动模拟插件的内省请求,直接用curl调用网关地址,验证接口是否正常:
curl -X POST 替换为你的网关GraphQL端点地址 \ -H "Content-Type: application/json" \ -d '{"query":"query IntrospectionQuery { __schema { queryType { name } mutationType { name } subscriptionType { name } types { ...FullType } directives { name description locations args { ...InputValue } } } } fragment FullType on __Type { kind name description fields(includeDeprecated: true) { name description args { ...InputValue } type { ...TypeRef } isDeprecated deprecationReason } inputFields { ...InputValue } interfaces { ...TypeRef } enumValues(includeDeprecated: true) { name description isDeprecated deprecationReason } possibleTypes { ...TypeRef } } fragment InputValue on __InputValue { name description type { ...TypeRef } defaultValue } fragment TypeRef on __Type { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } }"}'
如果curl请求返回错误,说明问题出在网关侧,和Gatsby配置无关。
常见问题及对应解决方法
针对Apollo Federation网关的场景,该错误多数为以下几种原因:
- 网关关闭了内省查询:生产环境的Apollo网关默认会关闭内省功能,而gatsby-source-graphql启动时必须先拉取schema。解决方案有两种:临时开启网关的
introspection配置;如果不能开启内省,可将本地导出的schema SDL文件路径配置到插件的localSchema参数,跳过远程拉取步骤。 - 缺少必要的请求头:如果网关配置了鉴权、UA校验、跨域校验,需要在插件配置中添加
headers参数传入对应请求头,示例配置如下:
module.exports = { plugins: [ { resolve: 'gatsby-source-graphql', options: { typeName: 'Gateway', fieldName: 'gateway', url: 'https://你的网关地址', // 添加需要的请求头 headers: { Authorization: 'Bearer 你的鉴权token', 'User-Agent': 'gatsby-source-graphql' } } } ] };
- 端点地址错误:确认配置的
url是网关的GraphQL服务端点,很多场景下需要加上/graphql后缀,不要填成网关的前端页面地址。 - Federation schema兼容性问题:如果网关返回的Federation格式schema和标准GraphQL内省格式有差异,可通过
createLink参数自定义Apollo请求链路来适配,不需要额外修改其他配置。
内容的提问来源于stack exchange,提问作者kemicofa
相关产品推荐
相关产品推荐

