在vue+express開發應用時碰見的history模式問題,vue官方提供的中間件能很好地解決問題。 只是本身的項目總有本身的問題。 中間件connect-history-api-fallback涉及到的主要問題是rewrites的配置問題。
本文主要內容是本身案例裏的解決方案。css
vue router 配置mode 爲 historyhtml
//index.js
export default new Router({
mode: "history",
routes: [
...
]
})
複製代碼
使用官方推薦中間件 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