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

NX Monorepo中NestJS+Apollo联邦网关Introspect子服务报400错误

问题排查与解决方案

1. 子服务与网关的GraphQL路径不匹配

网关请求auth子服务的地址是http://localhost:3100/apis/auth-service/graphql,先确认auth-service的GraphQLModule里的path配置是否和这个路径完全一致。如果子服务用的是默认的/graphql,那网关请求肯定会返回400错误。

2. Apollo联邦依赖版本不兼容

你的依赖里存在版本冲突:

  • @apollo/federation是0.37.1(旧版联邦),但@apollo/subgraph和@apollo/gateway是2.1.3(联邦v2)。Apollo联邦v2已经废弃了@apollo/federation,改用@apollo/subgraph,旧版依赖和v2网关/子服务不兼容。

解决办法:
卸载旧版联邦依赖,统一用v2版本:

npm uninstall @apollo/federation
npm install @apollo/subgraph@latest @apollo/gateway@latest

同时确保@nestjs/graphql和Apollo依赖兼容,10.x版本本身支持联邦v2,若有问题可以升级到最新兼容版。

3. 子服务未正确配置为联邦子服务

检查auth-service和user-service的GraphQLModule,必须用联邦方式生成schema,而不是普通schema。示例配置:

import { buildFederatedSchema } from '@apollo/subgraph';

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: true,
      // NestJS 10+ 可以直接用federation配置
      federation: {
        version: 2,
      },
      // 或者用transformSchema方式(兼容旧版)
      // transformSchema: (schema) => buildFederatedSchema({ schema }),
    }),
  ],
})
export class AuthModule {}

如果子服务没开联邦,网关的 introspection 请求会直接失败,返回400。

4. 网关配置存在语法和冗余项

你的网关配置有两个问题:

  • server里的autoSchemaFile在联邦网关模式下完全不需要,网关的schema是组合子服务生成的,本地生成的schema会冲突,直接删掉这个字段。
  • path: '/apis/gateway/graphql'末尾用了分号;,应该改成逗号,,语法错误会导致配置解析异常。

修正后的网关配置片段:

{
  server: {
    debug: true,
    playground: true,
    sortSchema: true,
    introspection: true,
    cors: ['*'],
    path: '/apis/gateway/graphql',
  },
  gateway: {
    supergraphSdl: new IntrospectAndCompose({
      subgraphHealthCheck: true,
      subgraphs: [
        {
          name: 'user',
          url: resolveSubgraphUrl('user'),
        },
        {
          name: 'auth',
          url: resolveSubgraphUrl('auth'),
        },
      ],
    }),
  }
}

5. 健康检查与跨域问题

网关开了subgraphHealthCheck: true,要确保子服务的健康检查端点(默认是/.well-known/apollo/server-health)能正常访问,同时子服务的CORS配置要允许网关的请求来源。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:05:23