如何使用 Apollo Server 提供 index.html 文件?

How to serve index.html file with Apollo Server?

我在 index.js 中有此代码:

const PORT = process.env.PORT || 5000;
server.listen(PORT).then({ url }) => {
  console.log(`Server running at url: ${url}`);
});

在本地开发中,当我在浏览器上访问 localhost:5000 时,我可以使用 GraphQL playground 进行测试。

现在,我刚刚完成了 Heroku 的部署。当我转到 URL 时,我看到: GET query missing. 我认为发生这种情况是因为 apollo 正试图打开 GraphQL 游乐场,但它在生产模式下被阻止了。

如何让阿波罗服务 client/index.html

注意:我也尝试将 index.html 放在根目录中,但没有任何改变。

我在一个教程视频里看到express这道题的答案是:

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

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

我不知道如何在 Apollo 中执行此操作。

独立的 Apollo 服务器不能用于提供静态文件或公开其他端点。如果你需要这个功能,你需要使用像 Express、Hapi 或 Koa 这样的 HTTP 框架,然后 use the appropriate Apollo Server integration.

使用 Express 的示例:

const server = new ApolloServer({ ... });

const app = express();

server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
  console.log(` Server ready at http://localhost:4000${server.graphqlPath}`)
);