简体   繁体   中英

Adding GraphQL subscriptions to the existing express app using single server

GraphQL playground subscription fails with 400 error code.

WebSocket connection to 'ws://localhost:3000/graphql' failed: Error during WebSocket handshake: Unexpected response code: 400

I have an existing code based on express. I've integrated Apollo v2 this way:

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 . All queries and mutations work as expected

Now I want to add subscriptions. Turns out I need to use an http server:

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 . 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.

Additional reading: Express.js - app.listen vs server.listen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM