问题
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);
回答1:
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>
来源:https://stackoverflow.com/questions/39789425/react-routes-are-not-working-in-facebooks-create-react-app-build