axios的二次封装

145 阅读2分钟
import axios from 'axios';
import { Message } from 'element-ui';
import Cookies from '@/utils/cookies';
import Sign from './sign';  // 根据路由更换http || https
import qs from 'qs'; // 加密处理
import router from '@/router';
const protocol = location.protocol; // protocol 属性是一个可读可写的字符串,可设置或返回当前 URL 的协议。

// 记录和显示错误
function errorLog(error, addStore = true) {
  // 错误显示提示
  Message({
    message: error.message,
    type: 'error',
    duration: 5 * 1000 // 显示的时机
  });
}

// 创建一个 axios 实例
let HttpURl = ''; // 请求的根地址  下面的操作是把对应的环境的url赋值给根地址

if (window.location.host.includes('localhost')) {  // 获取当前的域名  如果域名中有localhost 
  HttpURl = process.env.VUE_APP_BASE_API.replace('http:', protocol); // 开发环境的话http替换成当前的url地址
} else {
  HttpURl = window.location.origin + '/api/';  // 获取当前接口路径拼接上/api/ 
}

const service = axios.create({
  baseURL: HttpURl,
  timeout: 5000, // 请求超时时间
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 如果本地存在就去本地获取不存在获取默认值
    //判断文件格式  添加对应的请求头
    if (config.type === 'json') {
      config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    } else if (config.type === 'form') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    } else if (config.type === 'file') {
      config.headers['Content-Type'] = 'multipart/form-data';
    } else if (config.type === 'blod') {
      config.headers.responseType = 'arraybuffer';
    }
    // 参数签名处理
    config = Sign.init(config, process.env.VUE_APP_ID, process.env.VUE_APP_API_KEY, process.env.VUE_APP_SECRET_KEY, 'SHA256', '1.0');
    config.method === 'get'
      ? config.params = { ...config.params, ...config.data }
      : (config.data = (config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
        ? qs.stringify(config.data)
        : config.data));
    const token = Cookies.get('token');

    if (token) {
      // 让每个请求携带自定义 token 请根据实际情况自行修改
      config.headers.Authorization = 'Bearer ' + token;
    }
    config.headers.windowAppId = process.env.VUE_APP_ID;

    return config;
  },
  error => {
    // 发送失败
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
  // dataAxios 是 axios 返回数据中的 data
    const dataAxios = response.data;
  // 如果响应成功了 或者响应的文件格式是blob文件的(流文件)  就直接返回数据
    if (dataAxios.code === 0 || response.config.type === 'blod') return dataAxios; 
  //根据状态码判断响应失败的提示 (一般是参数错误的失败)
    Message({ 
      message: dataAxios.message,
      type: 'error',
      duration: 5 * 1000
    });
    return dataAxios;
  },
  error => {
    if (error && error.response) {
        //根据响应码判断失败的提示
      switch (error.response.status) {
        case 400: error.message = '请求错误'; break;
        case 401: error.message = '未授权,请登录';
          Cookies.remove('token');
          router.push('/login');
          break;
         case 403: error.message = '拒绝访问'; break;
         case 404: error.message = `请求地址出错: ${error.response.config.url}`; break;
         case 408: error.message = '请求超时'; break;
        case 500:

          const msg = error.response.data.message;

          const str = 'NormalException: ';

          if (msg.indexOf(str) > 0) {
            error.message = msg.substr((msg.indexOf(str)) + str.length, msg.length);
          } else {
            error.message = '服务器内部错误';
          }
          break;
        case 501: error.message = '服务未实现'; break;
        case 502: error.message = '网关错误'; break;
        case 503: error.message = '服务不可用'; break;
        case 504: error.message = '网关超时'; break;
        case 505: error.message = 'HTTP版本不受支持'; break;
        default: break;
      }

      // 收到401错误,直接跳转到登录页面
      // if (error.response.status === 401) {
      //   store.dispatch('user/logout');
      // }
    }
    errorLog(error); // 调用请求错误的函数
    return Promise.reject(error);
  }
);

function isJSON(str) {
  if (typeof str === 'string') {
    try {
      const obj = JSON.parse(str);

      if (typeof obj === 'object' && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }
}
export default service;

使用get请求

 static async 方法名() {
    return request({
      url: '/xxx/xxx/xxx', //地址
      method: 'get',
      type: 'json'
    });
  }

使用post请求

static async 方法名(data) {
    return request({
      url: '/hksznydatareport/exception/add',
      method: 'post',
      type: 'json',
      data //参数
    });
  }

blob文件

// excel导出   返回的是二进制流文件  需要使用type:blob
  static async PIGEXPORT(data) {
    return request({
      url: '/hksznydatareport/pig/exportExcel',
      method: 'get',
      type: 'blob', // blob文件
      data
    });
  }