import axios from 'axios'; import {toLogin} from "@/utils/permissions"; import {ElMessage} from "element-plus"; export class Interceptors { public instance: any constructor() { this.instance = axios.create({timeout: 1000 * 300}) this.initInterceptors() } public getInterceptors() { return this.instance } public initInterceptors() { // this.instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8' /** * 请求拦截器 * 每次请求前,如果存在token则在请求头中携带token */ this.instance.interceptors.request.use( (config: any) => { // if (!config.headers.Authorization) { // const token = sessionStorage.getItem('ax_token'); // if (token) { // config.headers.Authorization = token; // } else { // // @ts-ignore // delete config.headers.Authorization // } // } return config; }, (error: any) => { } ); // 响应拦截器 this.instance.interceptors.response.use( // 请求成功 (res: any) => { if (res.status === 200) { // if (res.data?.code === 402) { ElMessage.warning(res.data.message) sessionStorage.removeItem('sg_token') toLogin() } else { return res } } }, // 请求失败 (error: any) => { ElMessage.error(error) console.error('错误接口:' + error.config.url) // 对响应错误做点什么 return Promise.reject(error) }); } }