React routes are not working in facebook's create-react-app build
Asked Answered
P

1

2

I am using react router to define the routes. And i am using create-react-app for developments. My question is if i type the url for subpages in address bar and try to visit it works in development build but not in production build.

I am using a a simple express server for hosting the production build

var express = require('express'),
  app = express(),
  http = require('http'),
  httpServer = http.Server(app);

app.use(express.static(__dirname + '/build'));

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html');
});
app.listen(3001);
Popele answered 30/9, 2016 at 10:31 Comment(2)
Which URL? The main one - yourdomain.com/ or a sub-page - yourdomain.com/some/page/123?Tris
@HoriaComan sub-pagesPopele
T
4

You must configure your webserver to serve the same page for all the routes you've defined, or implement server-side rendering in React. The development webserver is probably configured as such, but the production one (Apache? Nginx? something else?) isn't. This question might help.

The reason why this is, is that React is used in building single page applications. You have a single traditional webpage, which loads some scripts - the output of your build process most likely, and then those scripts take care of everything else. This includes generating new DOM, making requests to the "server" for data, and even faking a multi-page app behaviour by manipulating the URL when views change. This last bit is what react-router does.

However, web servers are usually oblivious to these things. They know how to serve URLs. And when you request yourdomain.com/ they'll serve that main page, but when you request yourdomain.com/some/page/123 they won't know what to serve, unless specially configured. And one configuration is to also return the contents of the main page for these other URLs. React-router will pick up the URL and use the proper components, so everything will look OK>

Tris answered 30/9, 2016 at 10:46 Comment(1)
To be more specific, the author would want to change / to /* in the handler that serves index.html.Demodulator

© 2022 - 2024 — McMap. All rights reserved.