vue如何實現代理,並解決跨域
1、簡單配置
module.exports = {
devServer: {
// 配置服務器地址
proxy: 'http://localhost:4000'
}
}
優缺點:
缺點:
1、如果vue項目中public文件夾中默認有的資源,代理服務器會直接從public文件夾中尋找
2、只能配置一個代理,無法多代理配置
優點:
1、配置簡單
2、復雜配置
module.exports = {
devServer: {
proxy: {
'/api': {
// 放服務器地址
target: 'http://localhost:4000',
//開啟websocket服務,默認為true
ws: true,
/*改變服務器來源,
假設服務器端口號為http://81.24.56.211:4000,則它也變為http://81.24.56.211:4000
目的就是為了欺騙服務器,便於代理服務器直接訪問到服務器的地址
**/
changeOrigin: true,
// 用於修改路徑配置
pathRewrite:{'^/api':''}
},
'/foo': {
// 放其他額服務器地址
target: '<other_url>'
}
}
}
}
2.1 使用pathRewrite的意義
假設我們需要訪問服務器上“/students”請求,則有
// 假設我們有這樣一個請求
axios.get('http://localhost:4000/api/students').then(
success=>{
console.log("成功")
},
error=>{
console.log("失敗")
}
)
此時我們請求的是服務器上的/api/students路徑,這就不太對了,因此我們需要在配置的時候將/api默認給替換掉,所以我們有pathRewrite這樣一個配置項