1

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 ?

VersifiXion
  • 2,152
  • 5
  • 22
  • 40
  • 1
    Does this answer your question? [Deploying react app on github pages front and backend in the same repository](https://stackoverflow.com/questions/52969697/deploying-react-app-on-github-pages-front-and-backend-in-the-same-repository) –  Jan 01 '20 at 16:58
  • oh ok so I can't deploy backend with Github Pages, right. But I still have the same error with Heroku – VersifiXion Jan 01 '20 at 17:00
  • No, you can't deploy backend on GitHub pages. –  Jan 01 '20 at 17:06
  • Just looking at your repo, where are you running the server? –  Jan 01 '20 at 17:06
  • in package.json there's a script "server" : "node server.js" which runs the server in server.js file at the root – VersifiXion Jan 01 '20 at 17:08

1 Answers1

4

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

Matt Carlotta
  • 18,972
  • 4
  • 39
  • 51