123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- import axios from 'axios';
- // import {notify} from '@/utils/notify'
- 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 = localStorage.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) => {
- return Promise.resolve(res.data)
- },
- // 请求失败
- (error: { response: any; }) => {
- const { response } = error;
- if (response) {
- // 请求已发出,但是不在2xx的范围
- this.errorHandle(response);
- return Promise.reject(response.data);
- } else {
- //@ts-ignore
- // notify.warning('网络连接异常,请稍后再试!');
- // 抛出报错信息,在页面里需要接收
- return Promise.reject(error);
- }
- });
- }
- private errorHandle(res: any) {
- console.error('错误接口:' + res.data.path)
- // 状态码判断
- switch (res.status) {
- case 401:
- break;
- case 403:
- break;
- case 404:
- //@ts-ignore
- // notify.warning('请求的资源不存在');
- break;
- default:
- //@ts-ignore
- // notify.warning('连接错误');
- }
- }
- }
|