为什么我的GraphQL订阅在本地服务器上有效,但在实时服务器上部署时却无效

问题描述

我正在构建GraphQL服务器并在其中进行订阅。将服务器部署到本地计算机上并在Playground中检查订阅后,该服务器便开始工作,即,它侦听事件并获得新添加的数据。这意味着订阅实现是正确的,并且没有错。当我在本地(即本地主机)上运行时,订阅工作正常,但是当我在实时环境(Heroku)上部署服务器时,在Playground中收听订阅时会出现以下错误

{
  "error": "Could not connect to websocket endpoint wss://foodesk.herokuapp.com/graphql. Please check if the endpoint url is correct."
}

仅需了解更多信息,我的查询和变异也可在实时服务器上运行,只是订阅无法正常工作。

这是我的代码

/**
 * third party libraries
 */
const bodyParser = require('body-parser');
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const helmet = require('helmet');
const http = require('http');
const mapRoutes = require('express-routes-mapper');
const mkdirp = require('mkdirp');
const shortid = require('shortid');
/**
 * server configuration
 */
const config = require('../config/');
const auth = require('./policies/auth.policy');
const dbService = require('./services/db.service');
const { schema } = require('./graphql');

// environment: development,testing,production
const environment = process.env.NODE_ENV;


const graphQLServer = new ApolloServer({
  schema,uploads: false
});

/**
 * express application
 */
const api = express();
const server = http.createServer(api);

graphQLServer.installSubscriptionHandlers(server)

const mappedRoutes = mapRoutes(config.publicRoutes,'api/controllers/');
const DB = dbService(environment,config.migrate).start();

// allow cross origin requests
// configure to allow only requests from certain origins
api.use(function (req,res,next) {

  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin','*');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods','*');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers','*');

  // Pass to next layer of middleware
  next();
});

// secure express app
api.use(helmet({
  dnsprefetchControl: false,frameguard: false,ieNoOpen: false,}));

// parsing the request bodys
api.use(bodyParser.urlencoded({ extended: false }));
api.use(bodyParser.json());

// public REST API
api.use('/rest',mappedRoutes);

// private GraphQL API
api.post('/graphql',(req,next) => auth(req,next));

graphQLServer.applyMiddleware({
  app: api,cors: {
    origin: true,credentials: true,methods: ['POST'],allowedHeaders: [
      'X-Requested-With','X-HTTP-Method-Override','Content-Type','Accept','Authorization','Access-Control-Allow-Origin',],},playground: {
    settings: {
      'editor.theme': 'light',});

server.listen(config.port,() => {
  if (environment !== 'production'
    && environment !== 'development'
    && environment !== 'testing'
  ) {
    console.error(`NODE_ENV is set to ${environment},but only production and development are valid.`);
    process.exit(1);
  }
  return DB;
});

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)