vue axios的使用以及解決跨域問題
阿新 • • 發佈:2018-11-22
安裝axios(前提是已經安裝了vue)
npm install axios --save
使用axios
1. 先在main.js中呼叫
import axios from 'axios'
axios.defaults.baseURL = "http://www.xxx.com";
Vue.prototype.$http = axios;
2. 在Vue例項中使用
this.$http .post('/demo/xxx/xxx', { data: data }) .then(function(res) { console.log(res.data) }) .catch(function() { console.log("error"); });
但是呢,可能會遇上跨域問題
解決方法如下:
1. 修改main.js的程式碼
// axios.defaults.baseURL = 'http://www.xxx.com'
axios.defaults.baseURL = '/api'
2. 在config/index.js檔案中的proxyTable新增以下程式碼
'/api':{
target: "http://www.xxx.com",
changeOrigin:true,
pathRewrite:{
'^/api':''
}
}
原理:
因為我們給url加上了字首/api,我們訪問/demo/xxx/xxx就當於訪問了:localhost:8080/demo/xxx/xxx(其中localhost:8080是預設的IP和埠)
在index.js中的proxyTable中攔截了/api,並把/api及其前面的所有替換成了target中的內容,因此實際訪問url是http://www.xxx.com/demo/xxx/xxx
如有錯誤之處,請指出,互相學習。