安装
npm i axios vue-axios -S
(可以加上--save-exact
作为精确版本安装)
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
提供的API
request(config)
get(url, config)
delete(url, config)
head(url, config)
options(url, config)
post(url, data, config)
put(url, data, config)
patch(url, data, config)
all()
axios()
axios({
url: 'url',
method: 'get',
params: {
key: val
},
data: {
key: val
},
headers: {
key: val
}
})
.then(res => {})
.catch(err => {})
get()
axios.get('url', {
params: {
key: value
},
headers: {
key: value
}
})
.then(res => {})
.catch(err => {})
post()
axios.post('url', {
key: value
}, {
headers: {
key: value
}
})
.then(res => {})
.catch(err => {})
request 拦截器
axios.interceptors.request.use(
config => {
if (store.state.token) {
config.headers.Authorization = `token ${store.state.token}`;
}
return config;
},
err => {
return Promise.reject(err);
});
response 拦截器
axios.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response) {
switch (error.response.status) {
case 401:
}
}
return Promise.reject(error.response.data)
});