为什么我的 GraphQL 订阅在本地服务器上运行,但部署在实时服务器上时却不行

Why my GraphQL subscriptions are working on local server but not when deployed on live server

我正在构建一个 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, res, next) => auth(req, res, 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;
});

根据您的错误;

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

您的应用在 heroku 应用服务上 运行,即“herokuapp.com”。就此服务而言,您无法控制服务器配置。

在开发中,您在“ws://”协议下提供订阅服务,当您部署到 heroku 时,该协议会转换为安全版本“wss://”。我的解决方案需要您通过 ssh 访问服务器。这意味着您升级您的 heroku 订阅以获得具有专用 IP 地址的虚拟机或与此相关的任何其他云提供商。如果您已经准备好,请执行以下操作;

  1. 在虚拟机上托管您的应用程序并为其提供服务,然后将 apache 编辑为代理“yourdomain.com”,以便在可能的端口 3000 上为该应用程序提供服务,如下所示
<VirtualHost *:80>
 ServerName yourdomain.com
 ProxyPreserveHost on
 ProxyPass / http://localhost:3000/
 ProxyPassReverse / http://localhost:3000/
RewriteEngine on


</VirtualHost>
  1. 转到您的域注册商并添加一个子域,您将通过该子域为您的订阅提供服务,也就是网络套接字。 这是通过添加一个带有子域名的 A 记录来完成的,例如“websocket”指向您的 vm ip 地址。这将使“websocket。yourdomain.com”可供使用。

  2. 在您的服务器上安装 apache 服务器并包含虚拟主机,如下所示

<VirtualHost *:80>
 ServerName websocket.yourdomain.com
 ProxyPreserveHost on
 ProxyPass / ws://localhost:3000/
 ProxyPassReverse / ws://localhost:3000/
RewriteEngine on


</VirtualHost>
  1. 重新启动 apache 服务器

此时,您的应用在“yourdomain.com”上 运行,这也是您所有 graphql 突变和查询的服务点。但所有订阅都将在“websocket.yourdomain.com”建立,它将代理所有对“ws://”协议的请求,从而无错误地到达您的订阅服务器。

N/B Your client side code will use "wss://websocket.yourdomain.com" for subscription connections