简体   繁体   中英

Serving static React app from server, crashing on refresh

I have made a React app which is hosted on the same machine as my API server as guided by this tutorial .

My directories are set up in such way that

- root
  - server.js (entry for the API server)
  - app (for all back-end stuff)
  - client (directory for React app)
    - public (static files used in the front-end)
    - src (for all front-end stuff)
    - build (directory containing static build)
      - index.html (entry for front-end)
      - ... (other bundled stuff)

And I am serving a static copy of my React app in below method.

// server.js

const app = express();
if (process.env.NODE_ENV === 'production') {
    app.use(express.static('client/build'));
}

app.use('/api', routes); // for API routes

I am having a problem where, when I boot this up locally, (with NODE_ENV=production ) everything smooth and page refreshes do not break the app.

However, after I have deployed this to Elastic Beanstalk, page refreshes break the app with this html error message being displayed in the browser.

Cannot GET /{whichever url path I had prior to refresh}

I could see in the logs that browser tried to send a request to the server with GET /{url_pathname}

I initially suspected something going funny with having both React router and Express router but then again, I am confused why this is not consistent with the case in the localhost.

If you are using NGINX, you need to update the configuration file located at /etc/nginx/sites-available

        location / {
            try_files $uri $uri/ /index.html$is_args$args;
        }

Or this if your app is not located in the default directory, for example "app-location" you would get this.

location /app-location {
  root /var/www;
  index  index.html;
  try_files $uri $uri/ /app-location/index.html;
}

And restart nginx

sudo service nginx restart

If you are running a react app that basically runs on a single index file, then your middleware router should have a catch-all route that always points to that index file somewhere.

 app.get('/*',(req, res) => {
   res.sendFile(path.join(__dirname + '/client/build/index.html'))
 })

Please note that the current example is dependent on the path module...So:

import path from 'path'
// or
const path = require('path')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM