UNPKG

zcloud-ui

Version:

A Component Library for Vue.js.

109 lines (104 loc) 2.74 kB
/** * axios basic configuration */ import axios from 'axios'; // 环境配置 import { Environment } from 'zcloud-ui/src/config/index'; import Interceptor from './interceptor'; let instance = axios.create(); const TimeOut = 60000; // 初始化拦截器 new Interceptor({ TimeOut, axios: instance }); // eslint-disable-line no-new // 配置 const configuration = [ 'ignoreRepeat', // 忽略防止重复请求 'verifycode', // 验证码 'timeOut', // 超时 'authCode', // 按钮权限 'AuthCode', // 按钮权限 'Authorization', // token 'ignoreError', // 忽略报错 'returnAll', // 返回带code的信息全部信息 'inside' // 组件库内部调用必须加 ]; /** * 基础配置 * 更多配置请参考 https://github.com/axios/axios * @param {*} url 请求地址 * @param {*} data 参数 * @param {*} type 请求类型,默认post */ let Http = (url, data = {}, type = 'post', header = {}) => { // // 手动加入api // for (let key in data) { // if (data[key] && data[key].constructor === Object) { // data[key].api = url; // } // } const CancelToken = axios.CancelToken; let cancel = null, timer = null; if (typeof type === 'object') { header = type; type = 'post'; } let headers = { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json', 'Authorization': Environment.TOKEN || '', ...header }; // 添加header token let query; // 处理配置 for (let item of configuration) { if (data[item]) { if (item === 'authCode') { headers.AuthCode = data[item]; } else { headers[item] = data[item]; } delete data[item]; } } const apiNum = data.apiNum || 0; const hostUrl = data.hostUrl || ''; delete data.hostUrl; delete data.apiNum; if (!url.includes('http')) { if (Environment.AUTH_MENU_ID) { headers.AuthMenu = Environment.AUTH_MENU_ID; } query = hostUrl + Environment.URL_PREFIX_API[apiNum] + url; } else { query = url; } const config = { url: query, method: type, timeout: headers.timeOut || TimeOut, // 超时时间 headers: headers, responseType: 'json', validateStatus: function (status) { return status >= 200 && status < 300; // 默认的 }, maxRedirects: 5, cancelToken: new CancelToken(function executor (c) { cancel = c; }), cancel, timer }; if (type.toUpperCase() === 'POST') { config.data = data; } else if (type.toUpperCase() === 'GET') { config.params = data; } let response = null; try { response = instance(config); } catch (error) { response = Promise.reject(error); } return response; }; export default Http;