import Vue from "vue"; import router from "../../src/router/index"; import axios from "axios"; // 请求拦截 axios.interceptors.request.use( config => { config.data = JSON.stringify(config.data); config.headers = { "Content-Type": "application/json", token: localStorage.getItem("token") || "" }; return config; }, error => { return Promise.reject(err); } ); // 响应拦截 拦截器 axios.interceptors.response.use( response => {
console.log(response) if (response.data.type == 'ok') { localStorage.clear() sessionStorage.clear() router.replace({ path: "/login" }); } return response; }, error => { return Promise.reject(error); } ); export default axios
请求拦截可以携带token等一些信息发送给后台,可以在响应拦截里面监听后台返回的状态码,进行数据处理和特定的路由跳转