问题
<Router>
<Route exact path="/" component={App}/>
<Route path="/page1" component={Page1}/>
</Router>
页面的两个路由,点击导航可以正常显示每个路由页面,修改代码后,自动刷新浏览器,“/”home路由页面正常显示,
但是如果路由在page1页面下,刷新浏览器页面404。
问题分析
在刷新页面时,浏览器会向服务器请求localhost:8000/page1,服务器会去根目录下查找page1.html文件,发现找不到该文件,而服务器上实际上没有该物理路径,所有的路由页面实际上是根据react-router去渲染的,所以才会报404。
解决方法
- 通过修改webpack-dev-server运行方式
在运行时加入参数“–history-api-fallback”
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --env development --open --history-api-fallback",
"build": "rm -rf ./dist && webpack --env production"
}
- 修改Nginx配置
server {
server_name localhost;
listen 80;
root /Users/WEB-Project/React-Demo/dist;
index index.html;
location / {
try_files $uri /index.html;
}
}
- Node服务端配置
express配置
const express = require('express');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
//加载指定目录静态资源
app.use(express.static(__dirname + '/dist'))
//配置任何请求都转到index.html,而index.html会根据React-Router规则去匹配任何一个route
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'dist', 'index.html'))
})
app.listen(port, function () {
console.log("server started on port " + port)
})
koa配置
import Koa from 'koa';
import xtpl from 'koa-xtpl';
import path from 'path';
const app = new Koa();
const port = process.env.PORT || 8081;
app.use(xtpl({
root: path.resolve(__dirname, '../dist'),
extname: 'html',
commands: {}
}));
app.use(async(ctx, next) => {
await ctx.render('index', {});
});
app.listen(port, () => {
console.log('Server started on port' + port);
});
注意: 由于koa的这种方式端口与webpack-dev-server(8080)必须不同,所以还需要配合Nginx代理。例如:
server {
server_name react.thinktxt.com;
listen 80;
location / {
proxy_pass http://localhost:8081;
}
}
server {
server_name static.react.thinktxt.com;
listen 80;
location / {
proxy_pass http://localhost:8080;
}
}