前端配置:
①webpack.config.js中設置devServer項中proxy
// 以下的各種寫法都可以實現(xiàn):例如對 /api/users 的請求會將請求代理到 http://xxx.com/api/users
devServer:{
// 寫法一:
proxy: {
'/api': 'http://xxx.com/',
},
// 寫法二:
proxy: {
'/api': {
target: 'http://xxx.com/',
pathRewrite: { '^/api': '/api' },// http://xxx.com/api/xxx
// pathRewrite: { '^/api': '/' },// http://xxx.com/xxx
},
},
// 寫法三(可以將多個特定路徑代理到同一目標):
proxy: [
{
context: ['/api'],
target: 'http://xxx.com/'
},
],
}
// 輸出添加:publicPath: '/'
output: {
filename: 'js/[name].[hash].js',
path: path.resolve(__dirname, '../dist'),
publicPath: '/',
},
實踐過程中碰到了一個問題,就是這么配置context:['/'],結果刷新url變成了這樣(如下圖)。修改成context:['/api']就可以了

image.png
②此時刷新頁面刷新顯示Cannot Get(下圖)。解決方式:在webpack.config.js中設置devServer項中
historyApiFallback

image.png
// history模式下的url會請求到服務器端,但是服務器端并沒有這一個資源文件,就會返回404,所以需要配置這一項
historyApiFallback: {
//與output的publicPath有關(HTMLplugin生成的html默認為index.html)
index: '/index.html',
},
至此,前端部分配置完畢。但如果直接訪問http://xxx/home,靜態(tài)服務器會去目標目錄下尋找home文件,目標目錄下有這個文件嗎?沒有!所以自然就404了。所以Nginx添加如下代碼:
location / {
root /xxx/dist;// 包地址
try_files $uri $uri/ /index.html;
// $uri是nginx中的變量,比如我訪問的網(wǎng)址是http://xxx/home,那么它就代表的/home。
}