webpack提供了配置代理的方法解決跨域
1 在vue-cli項目中打開webpack.dev.cof.js,如下
2 打開conifg目錄下的index.js,在 proxyTable中進行配置

1 proxyTable: { 2 '/api': { 3 target: 'http://192.168.10.202:8080/',//設置你調用的接口域名和端口號 別忘了加http 4 changeOrigin: true, 5 pathRewrite: { 6 '^/api': '/'//這里理解成用‘/api’代替target里面的地址,后面組件中我們掉接口時直接用api代替 比如我要調用'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add’即可 7 } 8 } 9 },
1 proxyTable: { 2 '/api': { 3 target: 'http://192.168.10.202:8080/',//設置你調用的接口域名和端口號 別忘了加http 4 changeOrigin: true,//設置true 代表跨域訪問 5 secure: false, // 如果是https接口,需要配置這個參數 6 pathRewrite: { 7 '^/api': '/'//這里理解成用‘/api’代替target里面的地址,后面組件中我們掉接口時直接用api代替 比如我要調用'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add’即可 8 } 9 } 10 },
3 配置好后,就可以獲取后台提供的接口,然后進行頁面的渲染了
1 this.$http.get('/api/user/add') 2 .then(res=>{ 3 console.log(res); 4 }).catch(err=>{ 5 console.log(err); 6 });