说明
axios 有两大拦截器(同时存在):
- 请求拦截器
- 响应拦截器
在请求或响应被 then 或 catch 处理前拦截它们。
中文文档:
http://www.axios-js.com/zh-cn/docs/#%E6%8B%A6%E6%88%AA%E5%99%A8
作用
可以没有拦截器,但是需要自己手动写 重复代码
作用:就是 统一做处理,节省大量重复的代码
如:
- 每次发请求时,需要携带当前登录人的信息
- 对响应统一做处理,如:登录失败、注册失败、支付失败
vue脚手架工程导入axios
修改 main.js 文件,添加下面代码,导入 axios
import axios from 'axios'
添加请求拦截器
发请求时自动携带数据,如当前人登录名
代码
修改 main.js 文件,加上下面代码:
axios.interceptors.request.use(function (config) {
// 如:携带当前登录人姓名,注意请求头不能有汉字
config.headers['username'] = 'lilei'
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
添加响应拦截器
从服务器接收响应数据时,对数据 统一进行处理
如:判断 code 不为 0 时,说明请求出问题,比如登录失败、注册名字重复等
修改 main.js 文件,加上下面代码:
axios.interceptors.response.use(function (response) {
// 如:统一错误处理
if(response.data.code != 0){
alert(response.data.msg)
}
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
main.js 完整代码
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
axios.interceptors.request.use(function (config) {
// 如:携带token
config.headers['username'] = 'lilei'
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
// 如:统一错误处理
if(response.data.code !==100){
alert("数据格式错误!")
}
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
发请求
在其他组件发请求时,如下:
axios.get('json/student.json').then(function(res){
console.log(res);
console.log(res.data);
that.name = res.data.name
that.age = res.data.age
that.sex = res.data.sex
})
会自动进行请求拦截、响应拦截


