[英]Adding GraphQL subscriptions to the existing express app using single server
GraphQL playground subscription fails with 400 error code. GraphQL游乐场订阅失败,错误代码为400。
WebSocket connection to 'ws://localhost:3000/graphql' failed: Error during WebSocket handshake: Unexpected response code: 400
I have an existing code based on express. 我有一个基于express的现有代码。 I've integrated Apollo v2 this way: 我以这种方式集成了Apollo v2:
const { ApolloServer, PubSub, gql } = require('apollo-server-express');
...
const app = express();
const server = new ApolloServer({
typeDefs,
resolvers
});
server.applyMiddleware({ app });
...
app.listen(port, () =>
console.log(chalk.blue(`App listening on port ${port}!`)),
);
and then i start my existing app on port 3000
and can access the GraphQL playground on http://localhost:3000/graphql
. 然后在端口3000
上启动我现有的应用程序,然后可以访问http://localhost:3000/graphql
上的GraphQL游乐场。 All queries and mutations work as expected 所有查询和变异均按预期工作
Now I want to add subscriptions. 现在,我要添加订阅。 Turns out I need to use an http server: 原来我需要使用http服务器:
const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);
and then listen to it on another port: 然后在另一个端口上监听它:
httpServer.listen(3005, () => {
console.log(`Server ready at http://localhost:3005${server.graphqlPath}`);
console.log(`Subscriptions ready at ws://localhost:3005${server.subscriptionsPath}`);
});
So I have two servers running. 所以我有两个服务器在运行。 My own on port 3000
and the subscriptions server on 3005
. 我自己的端口为3000
,订阅服务器为3005
。 Is that the right way? 那是正确的方法吗? Is it the only way? 这是唯一的方法吗?
There's no need to call both app.listen
and httpServer.listen
-- calling httpServer.listen
will expose both your Express app and the subscription server. 无需同时调用app.listen
和httpServer.listen
-调用httpServer.listen
将同时显示Express应用程序和订阅服务器。
Additional reading: Express.js - app.listen vs server.listen 附加阅读: Express.js-app.listen与server.listen
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.