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

开始

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

vue

vue router 配置mode 为 historyhtml

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

node express

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

npm install --save connect-history-api-fallback
复制代码

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

//其余请求操做
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-fallbackgit

结束语

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

相关文章
相关标签/搜索