6
votes

I created a ReactJS application using Create-React-App, and wanted to deploy it on a Linux server. I followed a tutorial that showed how to do so very simply by installing pm2 and serve, then after running the command:

npm run build

I ran the command that actually hosted the application:

pm2 serve build

Now the problem is whenever I visit a url that is not the base one, or click reload from browser while I'm on a page other than home page, I get 404 not found error.

I understand the previous command is meant to serve a single page only. My question is: is there a way to make the url for example http://myserver:port/a go to Route a in my app? Or at least go to http://myserver:port/ ?

I already have Nginx installed on the same server, as I am using it to host a Flask Python app, but I'm very new to all this and I am looking for a simple way that works, as I faced some difficulties to get the Python app hosted.

Please note that I am only using React, no Redux, express, or any Database, if that is of any relevance. I am also using BrowserRouter inside my app.

3

3 Answers

4
votes

pm2 serve has a Single-Page-Application Mode (https://pm2.keymetrics.io/docs/usage/expose/#serving-spa-redirect-all-to-indexhtml)

From the docs:

To automatically redirect all queries to the index.html use the --spa option:

pm2 serve build --spa

Or if using ecosystem.config.js file:

module.exports = {
  script: "serve",
  env: {
    PM2_SERVE_PATH: 'build',
    PM2_SERVE_PORT: 8080,
    PM2_SERVE_SPA: 'true',
    PM2_SERVE_HOMEPAGE: '/index.html'
  }
}
1
votes

pm2 serve build just serves build folder statically. So http://myserver:port/a will request file named 'a' in build folder. If it doesnt find it, it returns 404

To make ur server able to handle other routes, you cannot use pm2 serve. Instead you should start your flask server through pm2. You may take a look at How to run a python script like pm2 for nodejs

1
votes

I use Vue.js, "npm run build" command generates static files into dist folder, the pm2 command looks like this:

pm2 --name <appName> serve --spa <staticFolder> <port>