vue-cli+webpack-simple建立專案訪問後臺(跨域問題解決)
阿新 • • 發佈:2019-01-06
在網上找了很多都是webpack在config目錄下的index.js裡面程式碼,這裡總結了一個webpack-simple跨域的問題,在webpack.config.js的devServer中配置:
devServer:{ port: 8080,//自己專案的埠 host: 'localhost',//自己專案的地址(注意:這裡不要加http協議) proxy: { '/api/*': { target: 'http://192.168.x.xxx:xxxx',//跨域要訪問的地址及埠 changeOrigin: true, secure: false, } } }
如果用的事axios訪問後臺的話,倘若同時請求多個介面,也會出現代理失敗的問題,這裡分享一個解決方法:
axios.all([
axios.post('/user1'),
axios.post('/user2'),
axios.post('/user3')
])
.then(axios.spread(function (cpResp, cgResp, pdResp) {
//回撥
}));
同時,後臺配置(java寫法)
response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("content-type", "text/html; charset=UTF-8");
注意:
- '/api/*'表示 ‘/api’ 請求都會被代理到 target: http://192.168.x.xxx:xxxx 中,如:localhost:8080/api/test會被代理到:http://192.168.x.xxx:xxxx/api/test;
- target裡面一定要把http帶上,我就是沒帶http然後搞了大半天!
- 如果有其他的方法大家可以留言交流。