隨手vue筆記 (三)
1、代理服務器 解決跨域問題 vue.config.js
在vue根目錄下新建一個 vue.config.js文件 ,文件內容如下:
方式一,當個服務
module.exports={ page:{ index:{ //入口 entry:'src/main.js' } }, lintOnSave:false, //關閉語法檢查 //開啓代理服務器 devServer:{ proxy:'http://localhost:5000' //後臺地址 } }
頁面請求內容
//前臺頁面內容 axios.get('http://localhost:5000/student').then(res=>res.data) //注意這裏不能是用5000了,改成8080 axios.get('http://localhost:8080/student').then(res=>res.data)
方式二,多個服務
module.exports={ //開啓代理服務器 devServer:{ proxy:{ '/api':{ target:'http://localhost:5000', pathRewrite:{'^/api':''},// 匹配一api開頭的路徑,把api變成 ''變成空字符串 ws:true, //用於開啓websecket changeOrigin:true //用於控制請求頭中的host值 }, '/demo':{ target:'http://localhost:5001', pathRewrite:{'^/demo':''}, //ws:true, //changeOrigin:true }, } } }
頁面請求
//頁面使用的時候 axios.get('/student').then(res=>res.data)