GraphQLServer + Socket-io在同一端口上

时间:2019-05-16 01:15:48

标签: node.js express heroku socket.io apollo

我有一个使用GraphQLServer的工作项目,它从端口4000服务我的react应用程序,并在端口5000上监听socket-io。

我正尝试部署到heroku,因此我需要它们位于同一端口上(process.env.PORT),但是我不知道如何使用GraphQLServer做到这一点。

This is how to do it with express + socket-io

This is the start script for GraphQLServer

Gist with my current code is here

相关代码:

import server from './server';
import express from 'express';
import path from 'path';

const http = require('http').Server(server.express);
const io = require('socket.io')(http);
require('./socket')(io);

server.express.use(express.static(path.join(__dirname, '../../client/build')));
server.express.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, '../../client/build', 'index.html'));
});

// Socket-io listener
http.listen({
    port: process.env.PORT || 5000
  }, () =>
  console.log('listening on port ' + process.env.PORT || 5000)
);

// GraphQL and app listener
server.start({
    cors: {
      credentials: true,
      origin: '/'
    }
    // port: process.env.PORT || 4000
  },
  () => {
    console.log('The server is up!');
  }
);

1 个答案:

答案 0 :(得分:0)

没有从graphql-yoga的开发人员那里得到任何输入,因此在prisma slack上被询问,建议使用apollo-server-express

我注意到切换到ApolloServer的主要变化是:

  1. 它通过{ req, res }而不是{ request, response }
  2. 您需要使用graphql-import导入架构,例如typeDefs: importSchema('./src/schema.graphql')

首先,我为socket-io创建一个快速应用程序和httpServer,并告诉io监听使用该应用程序实例化的httpServer

const app = express();
const httpServer = require('http').createServer(app);
const io = require('socket.io')(httpServer);
require('./socket')(io); // my io.on('connection', socket => {}) function taking io as param
io.listen(httpServer);

然后我应用所有中间件并使用应用设置路由

if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, '../../client/build')));
  app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, '../../client/build', 'index.html'));
  });
} else {
  app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '../../client/public', 'index.html'));
  });
}

app.use(cookieParser());

app.use((req, res, next) => {
  if (!req.cookies || !req.cookies.token) {
    return next();
  }
  const { token } = req.cookies;
  if (token) {
    console.log(process.env.PORT);
    const { userId } = jwt.verify(token, process.env.JWT_SECRET);
    // Put the userId onto the req for future requests to access
    req.userId = userId;
  }
  next();
});

最后(使用ApolloServer 2),我将应用程序作为中间件应用到ApolloServer,并告诉httpServer监听

import server from './server' // my ApolloServer

server.applyMiddleware({
  app,
  path: '/graphql',
  cors: {
    credentials: true,
    origin: process.env.DOMAIN_FULL + ':' + process.env.PORT || '3000'
  }
});

httpServer.listen({
    port: process.env.PORT || 4000
  },
  () => console.log(`Server is running on ${server.graphqlPath}`)
);

请确保您使用的是不带参数的io()实例化客户端,并且您的ApolloClient uri为'/graphql'