ApolloServerPluginLandingPageGraphQLPlayground致订阅失败求助
解决Apollo Server使用GraphQL Playground时WebSocket订阅连接失败的问题
添加ApolloServerPluginLandingPageGraphQLPlayground插件后订阅功能失效,核心原因是GraphQL Playground默认使用的WebSocket协议和你服务器端用graphql-ws实现的WebSocket服务不兼容:
- 你的代码采用官方推荐的
graphql-ws库(基于GraphQL over WebSocket Protocol标准) - GraphQL Playground默认使用旧的
subscriptions-transport-ws协议,两者协议不匹配导致连接失败。
解决方案:给Playground指定匹配的WebSocket协议
修改ApolloServerPluginLandingPageGraphQLPlayground的配置,明确指定WebSocket端点和使用的协议为graphql-ws:
// Set up ApolloServer. const server = new ApolloServer({ schema, plugins: [ ApolloServerPluginLandingPageGraphQLPlayground({ settings: { 'subscriptionsEndpoint': 'ws://localhost:4000/graphql', 'subscriptionProtocol': 'graphql-ws' } }), // Proper shutdown for the WebSocket server. { async serverWillStart() { return { async drainServer() { await serverCleanup.dispose(); }, }; }, }, ], });
原理说明
通过subscriptionProtocol: 'graphql-ws'配置,让Playground使用和服务器端一致的WebSocket协议标准,就能正常建立连接并处理订阅请求了。
内容的提问来源于stack exchange,提问作者Itamar Shubin
相关产品推荐
相关产品推荐

