interceptors.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import axios from 'axios';
  2. // import {notify} from '@/utils/notify'
  3. export class Interceptors {
  4. public instance: any
  5. constructor() {
  6. this.instance = axios.create({timeout: 1000 * 300})
  7. this.initInterceptors()
  8. }
  9. public getInterceptors() {
  10. return this.instance
  11. }
  12. public initInterceptors() {
  13. // this.instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
  14. /**
  15. * 请求拦截器
  16. * 每次请求前,如果存在token则在请求头中携带token
  17. */
  18. this.instance.interceptors.request.use(
  19. (config: any) => {
  20. if (!config.headers.Authorization) {
  21. const token = localStorage.getItem('ax_token');
  22. if (token) {
  23. config.headers.Authorization = token;
  24. } else {
  25. // @ts-ignore
  26. delete config.headers.Authorization
  27. }
  28. }
  29. return config;
  30. },
  31. (error: any) => {
  32. }
  33. );
  34. // 响应拦截器
  35. this.instance.interceptors.response.use(
  36. // 请求成功
  37. (res: any) => {
  38. return Promise.resolve(res.data)
  39. },
  40. // 请求失败
  41. (error: { response: any; }) => {
  42. const { response } = error;
  43. if (response) {
  44. // 请求已发出,但是不在2xx的范围
  45. this.errorHandle(response);
  46. return Promise.reject(response.data);
  47. } else {
  48. //@ts-ignore
  49. // notify.warning('网络连接异常,请稍后再试!');
  50. // 抛出报错信息,在页面里需要接收
  51. return Promise.reject(error);
  52. }
  53. });
  54. }
  55. private errorHandle(res: any) {
  56. console.error('错误接口:' + res.data.path)
  57. // 状态码判断
  58. switch (res.status) {
  59. case 401:
  60. break;
  61. case 403:
  62. break;
  63. case 404:
  64. //@ts-ignore
  65. // notify.warning('请求的资源不存在');
  66. break;
  67. default:
  68. //@ts-ignore
  69. // notify.warning('连接错误');
  70. }
  71. }
  72. }