場景
-
Vue2.6.12
-
模式:單頁面應用(SPA)模式
-
路由模式:history 模式
【問題一】 刷新頁面,出現 Cannot GET / xxx
【解決】 設置 historyApiFallback: true
webpack.config.js
devServer: {
...
historyApiFallback: true
...
}
【問題二】在問題一解決的基礎上增加代理(proxy)配置,刷新頁面,再次出現 Cannot GET / xxx
問題,並且控制台還有報錯信息
- 配置
webpack.config.js
devServer: {
...
historyApiFallback: true,
proxy: {
'/': {
target: 'http://localhost:3000',
}
},
...
}
- 問題
【解決】 設置 bypass
webpack.config.js
devServer: {
...
historyApiFallback: true,
proxy: {
'/': {
target: 'http://localhost:3000',
bypass: function (req, res, proxyOptions) {
if (req.headers.accept.indexOf('html') !== -1) {
return 'index.html'; // SPA,只有一個html頁面,所有都返回index.html頁面(個人理解)
}
},
}
},
...
}
附 HtmlWebpackPlugin
插件的配置
- 輸出的文件:index.html,所以上面
bypass
返回的是 index.html
new HtmlWebpackPlugin({
title: 'Scaffolds',
template: './public/index.ejs', // 指定模板html文件
filename: 'index.html', // 輸出的html文件名稱
favicon: './public/favicon.ico',
hash: true,
cache: true,
}),