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');
  }
};

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐