1.拦截器分为request请求拦截器和response响应拦截器
PS:request请求拦截器:发送请求前统一处理,如:设置请求头headers、应用的版本号、终端类型等。
response响应拦截器:有时候我们要根据响应的状态码来进行下一步操作,例如:由于当前的token过期,接口返回401未授权,那我们就要进行重新登录的操作。
2.main.js文件中(先安装axios)
import axios from 'axios'
// 给Vue函数添加一个原型属性$axios指向axios(全局使用axios)
// vue实例中直接用this.$axios就可以执行axios方法
Vue.prototype.$axios=axios
3.http request 请求拦截器
PS:发送请求之前判断是否存在token,除了登录页,其他页面请求头headers都添加token
// http request 请求拦截器
axios.interceptors.request.use(config => {
// 在发送请求之前做些什么
let pathname = location.pathname;
if(localStorage.getItem('token')){
if(pathname != '/' && pathname != '/login'){
config.headers.common['token'] = localStorage.getI