日期: 2021/07/05 天气:多云

背景

将原有的hash模式的路由,改为history模式,后台是node,需要利用connect-history-api-fallback包来配置

官方用法

github地址

  1. ①先下载包
  2. npm i connect-history-api-fallback --save
  3. ②在app.js的启动文件配置
  4. const express = require('express');
  5. const app = express();
  6. ③如果public下只部署了一个项目,且是根目录,为index.html,只需要采用默认设置,这个要在引入静态文件之前引用!
  7. app.use(history());
  8. 如果public下只部署了一个项目,且是根目录,为xxx.html,需要改下配置
  9. history({
  10. rewrites: [
  11. { from: /\/xxx/, to: '/xxx.html'}
  12. ]
  13. });

注意

如果一个public文件夹下部署了多个,比如admin/xxxx,member/xxx,配置为

  1. history({
  2. rewrites: [
  3. { from: /\/admin/, to: '/admin/index.html'},
  4. { from: /\/member/, to: '/member/index.html'},
  5. ]
  6. });

这样会报错,也算是一个小坑吧,
image.png
需要加一行代码:

  1. app.use(history({
  2. htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'],//这句很重要,能解决谷歌安全性问题
  3. rewrites: [
  4. { from: /\/admin/, to: '/admin/index.html'},
  5. { from: /\/member/, to: '/member/index.html'},
  6. ]
  7. }));