无法连接到 websocket 端点

Could not connect to websocket endpoint

运行 带有 apollo 的快速服务器并尝试添加订阅,但我在 playground Could not connect to websocket endpoint ws://localhost:4000/graphql. Please check if the endpoint url is correct. 上一直 运行 进入此错误。我不确定我错过了什么。这是服务器代码:

const { ApolloServer, PubSub } = require('apollo-server-express');
const mongoose = require('mongoose');
const app = require('./app');

const resolvers = require('./graphql/resolvers');
const typeDefs = require('./graphql/typeDefs');

const pubsub = new PubSub();
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }) => ({ req, pubsub }),
});

const port = process.env.PORT || 4000;
server.applyMiddleware({ app });

mongoose
  .connect(process.env.DB_URI_DEV, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  })
  .then(() => {
    console.log('DB Connected');
    return app.listen(port);
  })
  .then(() => {
    console.log(`We live now boys at ${port}`);
  })
  .catch((error) => {
    console.log(error);
  });

好的,开始使用了。为了启用订阅,我通过 http 的 createServer 创建了一个服务器,并将实例传递给 installSubscriptionHandlers。工作代码:

const pubsub = new PubSub();
  const server = new ApolloServer({
    typeDefs,
    resolvers,
    context: ({ req, connection }) => ({ req, pubsub, connection }),
  });

  const httpServer = http.createServer(app);

  const PORT = 4000;
  await server.start();
  server.applyMiddleware({ app });
  server.installSubscriptionHandlers(httpServer);

  try {
    httpServer.listen(PORT);
    console.log(`server ==> Look alive boys`);
  } catch (error) {
    console.log('Apollo server error');
    throw new Error(error);
  }

  try {
    await mongoose.connect(process.env.DB_URI_DEV, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
    });
    console.log('server ===> DB Connected');
  } catch (error) {
    console.log('DB error');
    throw new Error(error);
  }