interceptors.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import axios from 'axios';
  2. import {toLogin} from "@/utils/permissions";
  3. import {ElMessage} from "element-plus";
  4. export class Interceptors {
  5. public instance: any
  6. constructor() {
  7. this.instance = axios.create({timeout: 1000 * 300})
  8. this.initInterceptors()
  9. }
  10. public getInterceptors() {
  11. return this.instance
  12. }
  13. public initInterceptors() {
  14. // this.instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
  15. /**
  16. * 请求拦截器
  17. * 每次请求前,如果存在token则在请求头中携带token
  18. */
  19. this.instance.interceptors.request.use(
  20. (config: any) => {
  21. // if (!config.headers.Authorization) {
  22. // const token = sessionStorage.getItem('ax_token');
  23. // if (token) {
  24. // config.headers.Authorization = token;
  25. // } else {
  26. // // @ts-ignore
  27. // delete config.headers.Authorization
  28. // }
  29. // }
  30. return config;
  31. },
  32. (error: any) => {
  33. }
  34. );
  35. // 响应拦截器
  36. this.instance.interceptors.response.use(
  37. // 请求成功
  38. (res: any) => {
  39. if (res.status === 200) {
  40. //
  41. if (res.data?.code === 402) {
  42. ElMessage.warning(res.data.message)
  43. sessionStorage.removeItem('sg_token')
  44. toLogin()
  45. } else {
  46. return res
  47. }
  48. }
  49. },
  50. // 请求失败
  51. (error: any) => {
  52. ElMessage.error(error)
  53. console.error('错误接口:' + error.config.url)
  54. // 对响应错误做点什么
  55. return Promise.reject(error)
  56. });
  57. }
  58. }