1、使用场景
每次都要在请求中加入,token ,判断是否有登陆,如果vue系统中,所有的请求都加入token,比较麻烦,每次发送求加入,不过vue给我们 提供了一种方法, -----拦截器
(请求拦截器/响应拦截器)
拦截器在平时的项目中是较常使用的,可以说一个项目里必不可少。
2、配置和使用
以下是我一次项目中拦截器的写法
// 引入axios
import axios from 'axios'
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// console.log(config);
// 在发送请求之前做些什么
// headers: { Authorization: localStorage.getItem('toutiao_token') }
let token = localStorage.getItem('toutiao_token')
if (token) {
config.headers.Authorization = token
}
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// console.log(response);
// 对响应数据做点什么
if (response.data.message == "用户信息验证失败!" || response.data.message == "用户信息验证失败") {
Toast.fail(response.data.message);
// this.$router.push({ name: "login" });
// console.log('当前页面地址:', window.location.href);
window.location.href = '#/login?redirect_url=' + window.location.href
}
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
在这留下一个链接,拦截器的详细用法可以在这了解
链接:link