React-Router browserHistorys刷新浏览器页面404解决方案

1 篇文章 0 订阅
1 篇文章 0 订阅

问题

<Router>
  <Route exact path="/" component={App}/>
  <Route path="/page1" component={Page1}/>
</Router>

页面的两个路由,点击导航可以正常显示每个路由页面,修改代码后,自动刷新浏览器,“/”home路由页面正常显示,
但是如果路由在page1页面下,刷新浏览器页面404。
home页面
page1页面

问题分析

在刷新页面时,浏览器会向服务器请求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;
	}
}
 

参考文章

React-Router browserHistory浏览器刷新出现页面404解决方案

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值