First, the problem description
In an interview, the interviewer asked about the relationship between react and node routing.
Now Spa (single page app) is used more and more widely.
Node (background) and react (front-end) have their own routes, when I page access to a URL, where is the route exactly?
The answer is a higher priority for node routing
So it will often appear that react set the router, but there is a 404 when the access is refreshed.
Because when you refresh a URL, you first identify the route in node, because we don't set this route (just set it in react), so it appearsCan‘t not GET /xxx
Second, the solution
It may be thought that since node first processes the URL, I guarantee that the routing of node and react will be the same! This is a good error can also execute react routing.
Looks like it does work! But this is not only troublesome, and the official does not recommend!
Here are some ways to solve most of the simple scenarios:
2.1 Node (Express/koa) renders only HTML
This is the way I use it most often.
var express = require(‘express‘);
var router = express.Router();
/* GET home page. */
router.get(‘/‘, function(req, res, next) {
res.render(‘index‘);
});
After packing with Webpack (or not packaging), introduce the relevant JS in the root HTML template, and then node uses the root path/to match the HTML template. That way, node won't report 404.
2.2 When node returns 404, point to HTML
router.get(‘*‘,(ctx, next) => {
ctx.type = ‘html‘;
ctx.body = fs.createReadStream(‘./index.html‘);
});
2.3 Choosing the right routing method
hashRouter: Hash routes are hung on the server for all routes to the front-end
BrowserRouter: The history mode (browserrouter: Browser routing) changes the URL in such a way that the browser sends a request to the server, and if no static resources are matched, the same HTML page should always be returned.
For example, the comparison of the following two graphs:
Histroy Mode (browserrouter)
Hash mode
The image comes from two ways of React.js: Hashrouter
You can see that the hash route solves this problem, but the hash route is a little ugly./#/
When using Hashhistory, the browser will not send Request,react-router itself to render the corresponding module according to the URL, because there is a # presence.
Third, follow-up
Of course, the choice of routing is not limited to this, but also includes the need for on-demand loading, routing parameter usage, and so on.
The following explains why so many hashes appear on the hash routing path, and what are the causes and effects?
react-routeSome of the underlying principles and detailed usage can be consulted in this article:
《
Deep understanding of the React-router routing system
In Spa, node route priority is higher than react route