1、需求說明
在前后端分離開發中,前端發送ajax請求因為受到了瀏覽器同源策略的限制,會出現跨域的問題,在Vue專案中使用代理請求解決跨域問題,
如果使用vue/cli 4.x以上版本創建的Vue專案,在專案的根目錄中創建 vue.config.js 組態檔,
2、代碼實作
在Vue專案根目錄創建 vue.config.js 組態檔,配置代碼如下:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000', //服務端地址
ws: true,
changeOrigin: true, // 允許跨域
pathRewrite: {
'^/api': '' // 標識替換,使用 '/api' 代替真實的介面地址
}
}
}
}
}
使用axios請求代碼:
// 使用 '/api' 代替真實介面地址
// 真實地址為 http://localhost:3000/users/find
this.$axios.get('/api/users/find').then(res=>{
console.log(res)
})
代理配置的官方API地址: https://cli.vuejs.org/zh/config/#devserver-proxy
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/279291.html
標籤:其他
上一篇:Codeforces Round #717 (Div. 2) C. Baby Ehab Partitions Again
