nodejs express vue-router history 模式解决方案

2,505 阅读1分钟

开始

在vue+express开发应用时遇见的history模式问题,vue官方提供的中间件能很好地解决问题。 只是自己的项目总有自己的问题。 中间件connect-history-api-fallback涉及到的主要问题是rewrites的配置问题。
本文主要内容是自己案例里的解决方案。

vue

vue router 配置mode 为 history

//index.js
export default new Router({
  mode: "history",
  routes: [
    ...
  ]
})

node express

使用官方推荐中间件 connect-history-api-fallback

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

示例项目为单页应用(vue) 所有静态文件位于public/dist 下

//其他请求操作
app.use('/', indexRouter);
app.use('/service/users', usersRouter);
//get 请求静态文件 配置 
var history = require('connect-history-api-fallback');
app.use(history({
  rewrites: [
    {//访问路径含dist则继续访问
      from: /^\/dist\/.*$/,
      to: function(context) {
        return context.parsedUrl.pathname;
      }
    },
    {//后缀为js|css 访问dist下相应文件
      from: /^\/.*[js|css]$/,
      to: function(context) {
        return '/dist/'+context.parsedUrl.pathname;
      }
    },
    {//访问路径不含dist则默认访问/dist/index.html
      from: /^\/.*$/,
      to: function(context) {
        return '/dist/';
      }
    },
  ]
}));
app.use(express.static(path.join(__dirname, 'public')));

相关链接

vue官方中间件推荐
connect-history-api-fallback

结束语

期待留言以及更好的解决方案。
O(∩_∩)O谢谢!