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

NestJS本地开发中GraphQL Playground订阅无法连接WebSocket端点

GraphQL订阅无法连接websocket端点问题排查

问题描述

本地开发的NestJS项目中,云基础设施无异常,但GraphQL订阅在Playground中抛出错误:

Could not connect to websocket endpoint ws://localhost:3600/graphql. Please check if the endpoint url is correct.

相关代码及依赖

模块注册代码

GraphQLModule.forRootAsync<ApolloDriverConfig>({
  driver: ApolloDriver,
  imports: [YeoConfigModule],
  useFactory: (configService: YeoConfigService<AppConfig>) => {
    const config: ApolloDriverConfig = {
      debug: true,
      subscriptions: {
        'graphql-ws': true,
      },
      playground: true,
      autoSchemaFile: './apps/event-service/schema.gql',
      sortSchema: true,
      context: ({ req, res }) => ({ req, res }),
    };
    const origins = configService.get('CORS_ORIGINS')();
    config.cors = { origin: origins, credentials: true };
    //    config.path = '/apis/event-service/graphql';
    return config;
  },
  inject: [YeoConfigService],
});

应用启动代码

async function bootstrap(): Promise<void> {
  const app = await getApp();
  await app.listen(process.env.PORT ?? 3600);
}

bootstrap();

依赖版本

"graphql-ws": "5.11.2",
"graphql-redis-subscriptions": "2.5.0",
"@apollo/gateway": "2.1.3",
"@nestjs/graphql": "10.1.3",
"graphql": "16.5.0",

报错信息

{
  "error": "Could not connect to websocket endpoint ws://localhost:3600/graphql. Please check if the endpoint url is correct."
}

问题原因及解决方案

1. Websocket的CORS配置未单独设置

HTTP的CORS配置不会自动继承到websocket连接,需要在subscriptions的graphql-ws配置中单独指定CORS规则:

subscriptions: {
  'graphql-ws': {
    server: {
      cors: {
        origin: origins,
        credentials: true,
      },
    },
  },
}

2. 上下文处理未兼容Websocket连接

当前上下文函数只处理了HTTP的req和res参数,但websocket连接的上下文会传入client等参数,未兼容会导致连接初始化失败,修改上下文函数:

context: ({ req, res, client }) => ({ req, res, client }),

3. Apollo Server 4配置方式变更

@nestjs/graphql 10.x基于Apollo Server 4,subscriptions的配置需要更明确的server定义,而非简单设为true。可补充path字段明确端点路径:

subscriptions: {
  'graphql-ws': {
    path: '/graphql',
    server: {
      cors: {
        origin: origins,
        credentials: true,
      },
    },
  },
}

4. 依赖冲突或版本兼容性问题

  • 若项目未使用联邦网关功能,可暂时移除@apollo/gateway依赖,避免与GraphQL订阅功能冲突。
  • 确认@nestjs/graphql与graphql-ws版本兼容:@nestjs/graphql 10.x推荐搭配graphql-ws 5.x,若问题持续可尝试升级graphql-ws至最新兼容版本(如5.14.0)。

5. 全局中间件拦截Websocket请求

检查项目中是否存在全局中间件,是否对/graphql路径的websocket连接进行了拦截,确保中间件不对websocket请求做不必要的校验或过滤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:45:34