React-Router browserHistory浏览器刷新
2022-02-16 本文已影响0人
_静夜听雨_
在基于React-Router的SPA项目部署上线后,会出现刷新或访问具体路径时浏览器页面404的问题,本质上是由于所有的URL默认先经后端处理,而服务器上实际上没有该物理路径,所有的路由页面实际上是根据React-Router去渲染的。该问题通过如下方式解决:
通过修改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
访问任何URI都指向index.html,浏览器上的path,会自动被React-router处理,进行无刷新跳转。
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)
})