【问题标题】:Deploying react/apollo-server app onto Heroku在 Heroku 上部署 react/apollo-server 应用程序
【发布时间】:2019-10-21 10:37:12
【问题描述】:

我正在尝试将 react / apollo-server 全栈应用程序部署到 heroku。因此,我尝试从 express/apollo-server 后端提供静态客户端文件,如下所示:

const path = require('path');

const express = require('express');
const app = express();
const cors = require('cors');
const { ApolloServer } = require('apollo-server');

const { schema } = require('./schema');
const { resolvers } = require('./resolvers');

app.use(cors());

app.use(express.static('public'));

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'public', 'index.html'));
});

const server = new ApolloServer({
  typeDefs: schema,
  resolvers,
});

server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
  console.log(`????  Server ready at ${url}`);
});

由于某种原因,我不明白客户端在部署到 heroku 时没有提供服务。在 heroku URL 上我得到:GET query missing. 如果我在生产中将 graphql 设置为启用,我可以看到它,我可以解析数据。但是客户端没有呈现。我用 * 猜测 app.get 不起作用,然后 index.html 没有被捕获。

我该如何解决这个问题?

谢谢!

【问题讨论】:

    标签: reactjs express graphql apollo apollo-server


    【解决方案1】:

    您遇到的错误是因为您仅将 ApolloServer 中的 server 公开到端口 4000,而没有使用前端客户端应用程序公开 app。

    为了部署全栈应用程序,您还必须公开app,为此您可以使用ApolloServer 中的applyMiddleware 并绑定阿波罗服务器和前端客户端,例如:

    .....
    
    app.get('*', (req, res) => {
      res.sendFile(path.resolve(__dirname, 'public', 'index.html'));
    });
    
    const server = new ApolloServer({
      typeDefs: schema,
      resolvers,
    });
    
    server.applyMiddleware({
      path: '/my-frontend', // you should change this to whatever you want
      app,
    });
    
    app.listen({ port: process.env.PORT || 4000 }, () => {
      console.log(`?  Server ready at http://localhost:4000`);
    });
    

    现在您应该能够导航到 http://localhost:4000/my-frontend 并查看您的客户端应用程序。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 2022-06-29
      • 2017-12-01
      • 2023-03-03
      • 2017-08-21
      相关资源
      最近更新 更多