import axios from 'axios' import { trim } from './util' // 默认配置 axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8' const axiosInstance = axios.create({ baseURL: '/api', // 请求超时时间 timeout: 60000 }) // 添加请求拦截器 axiosInstance.interceptors.request.use(function (config) { // 服务端调用,使用全路径 if (window === undefined) { config.baseURL = import.meta.env.VITE_API_URL } // 导出处理 if (config.download === true) { config.responseType = 'blob' } // 参数去空格 if (config.trim === true) { if (config.data != null) { config.data = trim(config.data) } if (config.params != null) { config.params = trim(config.params) } } return config }, function (error) { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器 axiosInstance.interceptors.response.use(function (response) { // 下载接口处理 if (response.headers['x-opera-type'] === 'download') { if (response.config.responseType !== 'blob') { return Promise.reject(new Error('下载接口返回类型错误,请检查接口定义是否缺少download标识!')) } // Blob类型数据,导出下载文件时,如果接口未正确执行,返回类型为Blob return new Promise((resolve, reject) => { if (response.data.type !== 'application/json') { resolve(response) return } const blob = new Blob([response.data]) const fileReader = new FileReader() // 读取Blob内容 fileReader.readAsText(blob, 'utf-8') fileReader.onload = function () { const result = JSON.parse(fileReader.result) // 业务失败 if (!result.success) { reject(result) return } resolve(result) } }) } // 对响应数据做点什么 if (response.data.success) { return response.data.data } console.error('接口错误', response.data.message) return Promise.reject(response.data) }, function (error) { if (error.response.status === 500) { return Promise.reject(new Error('网络繁忙,请稍后再试!')) } // 对响应错误做点什么 return Promise.reject(error) }) export default axiosInstance