首页 > 技术文章 > nodejs 解决 vue,react history 模式,刷新404问题

liangziaha 2021-10-03 15:01 原文

首先我们要明白一点,history 模式为什么刷新会404

1、vue,react :history模式是采用浏览器的历史记录,浏览器窗口有一个history对象,用来保存浏览历史

2、history渲染页面:当我们使用后端渲染页面: /build/index.html 时

  (1)例如:nodejs 渲染 index.html, 直接使用开放静态资源 app.use('/',express.static(path.join(__dirname, 'build')))  ,这样默认 “/” 路径即可访问 index.html 页面

  (2)但是当我们路由跳转时,从路由“/” 跳转到 “list”时,这时刷新页面 “/list” 就不会渲染 index.html 页面了,因为路径改变了,就不会渲染index.html 了

3、hash渲染页面:当我们使用后端渲染页面: /build/index.html 时,因为使用的hash 模式路径并不会改变,会由路由 “/#/” 跳转到 “/#/list”,注意这里只是改变的hash值,后端并不读取hash值,所以还是根据路由 “/” 进行渲染 index.html

 

 

解决 vue,react history 模式

1、(Express 框架 官方推荐)使用第三方库   connect-history-api-fallback

 

(1)安装  connect-history-api-fallback

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

(2)在app.js文件中使用

const history = require('connect-history-api-fallback')
app.use('/', history());

(3)history() 传入参数覆盖默认的索引文件(我们知道 express.static 静态资源默认索引文件为index.html )

history({
  index: '/default.html'
});

(4)history() 传入参数,根据url匹配 regex 模式时,重写索引。可以重写为静态字符串,也可以使用函数转换传入请求

history({
  rewrites: [
    { from: /\/soccer/, to: '/soccer.html'}
  ]
});

 

2、使用 app.all('*') 监听所以请求   注意:一定写到所有后端接口路由最后面 !!!前台页面路由,不能和后端接口路由重复,不然会响应接口数据

// 处理vue项目路由 history 模式问题 !!! 注意:一定写到所有后端接口路由最后面(前台页面路由,不能和后端接口路由重复 )
app.all('*',(req, res, next)=>{
  res.set({
    'Content-Type': 'text/html; charset=utf-8'
  })
  res.sendFile(path.join(__dirname, '/build/index.html'));
})

 

推荐阅读