客户端BrowserRouter路由模式部署上线,页面刷新404Not Found

241 阅读1分钟

1. 问题现象

客户端BrowserRouter路由模式部署上线,页面刷新404Not Found

2. 产生原因

  1. Vue或者React的SPA(单页面应用)应用打包;
  2. 部署到后端应用的静态托管服务上去;
  3. 当前端访问该应用时,根据前端路由访问静态服务资源;
  4. 静态服务资源只有打包后文件中的一个和他们了文件index.html;
  5. '/'访问对应index.html文件,存在该文件,此时刷新不会404;
  6. '/xxx/xxx'访问对应静态服务器时,在刷新后访问是找不到对应路径在服务端的html文件的,刷新页面会404;

3. 解决思想

将前端应用路由的请求指向到所部署的静态服务器中打包应用的index.html文件。

4. 部署案例

4.1 在koa2中部署前端应用

安装包

npm install --save 'koa2-connect-history-api-fallback'

实现代码

应用程序入口文件中

const Koa = require('koa');
const { historyApiFallback } = require('koa2-connect-history-api-fallback');
const app = new Koa(); // 实例化
// 此中间件需在静态服务器中间件前使用,whiteList(白名单)中的路由不会被指向到打包应用的**index.html**文件。
app.use(historyApiFallback({ whiteList: ['/api','/images'] }));

// other middlewares
app.use(...);

4.2 在express中部署前端应用

安装包

npm install --save 'connect-history-api-fallback'

实现代码

应用程序入口文件中

const express = require("express");
const history = require("connect-history-api-fallback"); 
const app = express();

// 使用history中间件 
app.use(history()); 

// 配置静态资源文件 
app.use(express.static(__dirname + "/public"));