vue全家桶安裝axios及使用代理跨域
axios提供了一下幾種請求方式
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
npm install axios --save-dev
然後在在main.js引入axios
import axios from 'axios'
Vue.prototype.$axios=axios
// 為給定 ID 的 user 建立請求
this.$axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可選地,上面的請求可以這樣做
this. $axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
this.$axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
在config/index.js
dev: {
// 加入以下
proxyTable: {
'/api': {
target: 'http://www.xxxx.con/',//設定你呼叫的介面域名和埠號 別忘了加http
changeOrigin: true,
pathRewrite: {
'^/api': '/'
//這裡理解成用‘/api’代替target裡面的地址,
// 後面元件中我們掉介面時直接用api代替 比如我要調
// 用'http://www.xxx.com/user/add',直接寫‘/api/user/add’即可
}
}
},