Issue when deploying with Heroku (Error 504)

蹲街弑〆低调 提交于 2020-01-06 04:56:06

问题


I'm deploying a very small React App + Node server to test deployment with Heroku,

I can get the client but not the server,

Repo : https://github.com/Versifiction/ofilms-test-heroku

Website : https://test-ofilms-heroku.herokuapp.com/

In the console, there's a 504 error

Failed to load resource: the server responded with a status of 504 (Gateway Timeout)
xhr.js:166 GET https://test-ofilms-heroku.herokuapp.com/api/message 504 (Gateway Timeout)

Do you know what I have to add to correct this 504 error ?


回答1:


Got some time to take a look at your repo. It's not the setupProxy.js, but instead it's how you've set up your API.

First issue: You're trying to serve production assets in development.

  app.use(express.static(path.join(__dirname, "build")));

  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "build", "index.html"));
  });

Fix: When you're in production, it'll capture requests and fallback to the client index.html if a requested route doesn't match.

if (process.env.NODE_ENV == "production") {
  app.use(express.static(path.join(__dirname, "build")));

  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "build", "index.html"));
  });
}

Second issue: You're serving the above assets as a wildcard / (changed to *) before you're serving your API routes. In other words, it'll never reach your GET requested API routes since / (*) catches all GET requests first.

Fix: All of your API routes must sit above your client production build -- this way, requests flow through the API first and then fallback to the client second.

app.get("/api/message", (req, res) => {
  res.json({ message: "Test déploiement d'O'Films sur Heroku" });
});

app.get("/api/hello", (req, res) => {
  res.json({ message: "Hello world !" });
});

if (process.env.NODE_ENV == "production") {
  app.use(express.static(path.join(__dirname, "build")));

  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "build", "index.html"));
  });
}

app.listen(port, () => {
  console.log(`Server is on up ${port} now !`);
});

Working example repo: https://github.com/mattcarlotta/ofilms-refactored



来源:https://stackoverflow.com/questions/59554351/issue-when-deploying-with-heroku-error-504

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!