Vue3+vite 配置axios二次封装

main.js中

  1. 安装依赖,引入axios

npm i axios --save
  1. 封装http.js

import Axios from 'axios';
import config from '@/config';
import { ElMessage } from 'element-plus'
import cookie from '@/lib/cookie';
import store from '@/store';
export const baseUrl = import.meta.env.VITE_API_DOMAIN;
let axios = Axios.create({
  baseURL: baseUrl,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
});
axios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    if (cookie.getToken()) {
      config.headers['x-access-token'] = cookie.getToken();
    }
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
// 添加响应拦截器
axios.interceptors.response.use(
  res => {
    if (res.config.responseType === 'blob') {
      let isReturnJson = res.headers && res.headers['content-type'] && res.headers['content-type'].indexOf('json') > -1;
      // 后端返回错误信息
      if (isReturnJson) {
        let reader = new FileReader();
        reader.onload = function (event) {
          let content = reader.result;
          let parseRes = JSON.parse(content); // 错误信息
          return validateResponseCode({
            data: parseRes
          });
        };
        reader.readAsText(res.data);
        return true;
      } else {
        // 下载文件
        download(res);
      }
    } else {
      // 正常json请求
      return validateResponseCode(res);
    }
  },
  error => {
    if (error && error.response && error.response.status) {
      if (error.response.status === 401) {
        cookie.clearToken();
        localStorage.clear();
        store.commit('setToken401', true);
      }
    }
    return true;
  }
);

function validateResponseCode (res) {
  let {
    data
  } = res;
  if (data && data.code && data.code !== 1) {
    if (data.code === 1001 || data.code === 998) {
      cookie.clearToken();
      localStorage.clear();
      store.commit('setToken401', false);
      return;
    } else if (data.code === 502) {
      window.location.href = window.location.pathname + '#/500';
      return;
    } else {
      ElMessage.error(data.msg)
      return Promise.reject(res);
    }
  }
  return Promise.resolve(data);
}

function blobToText (blob) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.readAsText(blob);
    fileReader.onload = function () {
      try {
        const result = JSON.parse(this.result);
        if (result && result['resultCode'] === 'fail') {
          resolve(result);
        } else {
          reject();
        }
      } catch (e) {
        // TODO handle the exception
        reject();
      }
    };
  });
}

export const postAxios = (url, data) => {
  return axios.post(url, data);
};

export const putAxios = (url, data) => {
  return axios.put(url, data);
};

export const deleteAxios = (url, data) => {
  return axios.delete(url, data);
};

export const postFileUploadAxios = (url, data) => {
  return axios.post(url, data, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
};

export const postDownloadAxios = (url, data) => {
  return axios.post(url, data, {
    responseType: 'blob'
  });
};

export const postDownloadAxios4Arraybuffer = (url, data) => {
  return axios.post(url, data, {
    // headers:
    //         {
    //             //'Content-Disposition': "attachment; filename=template.xlsx",
    //             'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    //         },
    responseType: 'arraybuffer'
  });
};

export const getAxios = (url, data) => {
  return axios.get(url, {
    params: data
  });
};


3.vite.config.js 配置代理

proxy: {
    // 引入api
    "/api": {
        target: "https://v2.alapi.cn",
        changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api/, ""),
        },
},
  1. api接口封装

import { postAxios, getAxios, putAxios, deleteAxios } from '@/utils/http';
export const apiUrl = {
  // 请求示例demo
  queryApi: () => {
    return getAxios('/api/common/a/b');
  }
};

你可能感兴趣的:(vue3,axios,前端框架,vue.js,前端)