api---config.js

 

完整的代码, 可以复制引用

vue2的axios http请求配置

import axios from 'axios';
import store from './store'; 
import { Toast } from 'path-to-toast-component'; // 全局Toast组件

// 创建一个axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // 基础url
  timeout: 5000 // 请求超时时间
});

// 用于存储每个请求的取消函数
const pending = [];
const CancelToken = axios.CancelToken;
let cancel;

// 获取请求的唯一标识
const getIdentifier = config => `${config.url}&${config.method}`;

// 移除已经完成的请求
const removePending = config => {
  for (let p in pending) {
    if (pending[p].u === getIdentifier(config)) {
      pending[p].f(); // 执行取消操作
      pending.splice(p, 1); // 从数组中移除这个请求
    }
  }
};

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 取消重复的请求
    removePending(config);

    config.cancelToken = new CancelToken(c => {
      pending.push({ u: getIdentifier(config), f: c });
    });

    // 为请求头添加token,假设您使用token进行身份验证
    const token = store.getters.token;
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    }

    return config;
  },
  error => {
    // 请求错误处理
    Toast.show({ message: '请求错误', duration: 3000 });
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 移除完成的请求
    removePending(response.config);
    
    // 假设您的数据结构为: { success: true, data: {}, message: '' }
    if (!response.data.success) {
      Toast.show({ message: response.data.message, duration: 3000 });
      return Promise.reject(new Error(response.data.message));
    }

    return response.data;
  },
  error => {
    // 响应错误处理
    if (axios.isCancel(error)) {
      console.log('Repeated request: ' + error.message);
    } else {
      Toast.show({ message: '响应错误', duration: 3000 });
    }

    return Promise.reject(error);
  }
);

export default service;

posted on 2020-04-28 22:34  完美前端  阅读(851)  评论(0)    收藏  举报

导航