axios请求拦截器和响应拦截器

import axios from 'axios';

const service = axios.create({
  baseURL: 'http:// test.com/api/',
  headers: { 'X-Requested-With': 'XMLHttpRequest' },
  withCredentials: true,
  timeout: 10000,
});

service.interceptors.request.use(
  config => {
    config.headers.Authorization = localStorage.getItem('Token');
    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

service.interceptors.response.use(
  res => {
    if (!res.headers['content-type']?.includes('application/json')) {
      // 非JSON类型,返回原始数据自行处理
      return res;
    }
    const { data } = res.data;
    if (!data) {
      throw new Error('请求繁忙,请稍候再试~');
    }
    return res.data;
  },
  error => {
    return Promise.reject(error);
  },
);

在main.js中引入,axios按需配置

posted @ 2022-10-26 11:19  hwinter_c  阅读(304)  评论(0编辑  收藏  举报