@10yun/cv-js-utils
Version:
常用 js-utils 工具类库
400 lines (388 loc) • 11.7 kB
JavaScript
/*
* 收集错误信息
*/
const EnumStatus = {
400: '请求错误',
400: '无效请求',
401: '未授权,请重新登录',
401: '未经授权,没有权限',
403: '拒绝访问',
404: '请求出错',
408: '请求超时',
500: '服务器错误',
501: '服务未实现',
502: '网络错误',
503: '服务不可用',
504: '网络超时',
505: 'HTTP版本不受支持',
10001: '未登录',
10002: 'token过期',
10009: '退出登录'
};
// 添加加载状态标识
var loadingWin = false;
class RequestClass {
constructor(options = {}) {
this.storeHandle = options.storeHandle || null;
this.flagMap = options.flagMap || {};
this.baseURL = options.baseURL || '';
this.requests = Object.assign({}, {}, options.requests || {});
this.headers = Object.assign({}, {}, options.headers || {});
this.canshuOpt = {};
this.retries = 3;
this.debugState = options.debug || false;
this.requestHandle = null;
/* 新创建 axios 实例配置 */
this.creSett = Object.assign(
{},
{
timeout: options.timeout || 5000, // request timeout
// 表示跨域请求时是否需要使用凭证;
// 开启withCredentials后,服务器才能拿到你的cookie
// 当然后端服务器也要设置允许你获取你开启了才有用
// withCredentials: true, // 开启跨域身份凭证
retry: 2
},
{}
);
this._initReqHandle();
}
debugLog() {
if (this.debugState) {
console.log('[调试]', ...arguments);
}
}
/* 初始化 request 句柄 */
_initReqHandle() {}
/**
* 请求成功
*/
netResponseOK(response) {
this.debugLog('netResponseOK ', response);
// 请求异常
const responseStatus = response.status;
if (responseStatus !== 200) {
this.resetNetError({ type: 'error', message: '请求异常' });
return Promise.reject(error);
}
return this.resetNetResponse(response.data);
// return response;
}
/**
* 请求失败
*/
netResponseError(error) {
this.debugLog('netResponseError ', error);
const errMsg = error?.message || '';
const responseStatus = error?.response?.status || 0;
const responseMsg = error?.response?.statusText || '';
// 服务器异常,请联系管理员
let lastMsg = '请求异常,请检查网络或联系管理员';
if (EnumStatus[responseStatus]) {
// 错误状态码 - 匹配
lastMsg = EnumStatus[responseStatus];
} else {
// 错误状态码 - 无匹配
if (errMsg.includes('Network Error')) {
lastMsg = '网络异常';
} else if (errMsg.includes('Not Found')) {
lastMsg = '未找到该请求';
} else if (errMsg.includes('timeout')) {
lastMsg = '请求超时,请刷新重试';
}
}
this.resetNetError({ type: 'error', message: lastMsg, status: responseStatus, error: errMsg });
// 错误抛到业务代码
return Promise.reject(error);
// return new Promise((resolve, reject) => {
// this.resetNetError({ type: 'error', message: lastMsg, status: responseStatus, error: errMsg });
// return reject({ error });
// });
}
/***
* ================== ================== ================== ==================
* 允许重写
* ================== ================== ================== ==================
*/
/**
* 设置错误时响应
*/
resetNetError(error) {
console.log(error.msg);
}
/**
* 设置网络请求响应
* 设置自定义业务响应
*/
resetNetResponse(apiResData) {
// 修改请求状态
// loadingWin = false;
let apiResStatus = apiResData.status || apiResData.code || -1;
apiResStatus = parseInt(apiResStatus);
// 这里根据后端提供的数据进行对应的处理
switch (apiResStatus) {
// 没有凭证,请登录
case 100101:
this.resetNetError({ type: 'error', message: apiResData.msg });
break;
// 无效凭证,请重新登录
case 100102:
this.resetNetError({ type: 'error', message: apiResData.msg });
break;
// 凭证过期,请重新登录
case 100103:
window.location.href = '/';
break;
// 无效凭证,请重新登录
case 100109:
break;
case 10009: // 退出登录
window.location.href = '/';
break;
case 404:
case 100404:
let msg404 = apiResData.msg || '操作失败';
this.resetNetError({ type: 'error', message: `${msg404}` });
return Promise.reject(apiResData);
break;
// 处理成功
case 200:
return apiResData;
break;
// 调试
case -1:
return Promise.reject({ msg: 'error' });
break;
default:
return apiResData;
break;
}
}
/**
* 调用 API 统一 请求 方法
*
* @author ctocode-zhw
* @version 2018-12-20
* @param apiUrl 不需要域名,域名统一拼接,只填写相关请求接口 【必须】
* @param reqData 提交参数
* @return
*
*/
apiAll(type, apiUrl, reqData) {
if (apiUrl.includes('http://') || apiUrl.includes('https://')) {
// apiUrl = apiUrl
} else {
apiUrl = this.baseURL + apiUrl;
}
//
/**
* 使用正则表达式进行过滤
* 过滤除了 https:// 和 http:// 以外的 // 和 ///
*/
apiUrl = apiUrl.replace(/([^:]\/)\/+/g, '$1');
/**
* 过滤除了 https:// 和 http:// 以外的 // 和 ///,但保留 ? 后面的内容
* apiUrl = apiUrl.replace(/^(https?:\/\/[^/]+)\/+/g, '$1/');
*/
// this.requestHandle.defaults.headers = this.headers;
let canshuOpt = this.canshuOpt || {};
this.canshuOpt = {};
let lastMethod = '';
if (type == 'POST') {
lastMethod = 'POST';
} else if (type == 'GET') {
lastMethod = 'GET';
} else if (type == 'PUT') {
lastMethod = 'PUT';
} else if (type == 'PATCH') {
lastMethod = 'PATCH';
} else if (type == 'DELETE') {
lastMethod = 'DELETE';
} else if (type == 'UPLOAD') {
lastMethod = 'POST';
this.headers['Content-Type'] = 'multipart/form-data';
}
return this.ExternalRequestFunc(apiUrl, {
// baseURL: this.baseURL || '',
method: lastMethod,
params: reqData,
headers: this.headers
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
// 'Accept': 'application/json, text/javascript, */*; q=0.01',
// }
})
.then((response) => {
const responseError = response?.error._rawValue || null;
const responseData = response?.data._rawValue || null;
const responseStatus = response?.status._rawValue || '';
if (responseStatus == 'error') {
return this.netResponseError({
status: 500,
message: responseStatus
});
}
if (responseData && responseStatus == 'success') {
return this.netResponseOK({
status: 200,
data: responseData,
message: responseStatus
});
}
})
.catch((error) => {
return Promise.reject(error);
});
}
/**
* GET 请求
*/
flagGet() {
const argumentsArr = arguments;
return this.unifyApi('flag', 'GET', argumentsArr);
}
urlGet() {
const argumentsArr = arguments;
return this.unifyApi('url', 'GET', argumentsArr);
}
/**
* POST 请求
*/
flagPost() {
const argumentsArr = arguments;
return this.unifyApi('flag', 'POST', argumentsArr);
}
urlPost() {
const argumentsArr = arguments;
return this.unifyApi('url', 'POST', argumentsArr);
}
/**
* PUT 请求
*/
flagPut() {
const argumentsArr = arguments;
return this.unifyApi('flag', 'PUT', argumentsArr);
}
urlPut() {
const argumentsArr = arguments;
return this.unifyApi('url', 'PUT', argumentsArr);
}
/**
* PATCH 请求
*/
flagPatch() {
const argumentsArr = arguments;
return this.unifyApi('flag', 'PATCH', argumentsArr);
}
urlPatch() {
const argumentsArr = arguments;
return this.unifyApi('url', 'PATCH', argumentsArr);
}
/**
* DELETE 请求
*/
flagDel() {
const argumentsArr = arguments;
return this.unifyApi('flag', 'DELETE', argumentsArr);
}
urlDel() {
const argumentsArr = arguments;
return this.unifyApi('url', 'DELETE', argumentsArr);
}
/* 文件上传通用 */
flagUpload() {
const argumentsArr = arguments;
return this.unifyApi('flag', 'UPLOAD', argumentsArr);
}
urlUpload() {
const argumentsArr = arguments;
return this.unifyApi('url', 'UPLOAD', argumentsArr);
}
/* 图片上传通用 */
flagUpImg() {
const argumentsArr = arguments;
return this.unifyApi('flag', 'UPLOAD', argumentsArr);
}
urlUpImg() {
const argumentsArr = arguments;
return this.unifyApi('url', 'UPLOAD', argumentsArr);
}
/**
* 统一请求
*/
unifyApi(flagOrUrl, methodType, argumentsArr) {
let _this = this;
let argNum = argumentsArr.length || 0;
if (argNum <= 0 || argNum > 3) {
let errorMsg = `-- ${methodType} : 参数为(1-3)个---`;
return new Promise((resolve, reject) => {
this.resetNetError({ message: errorMsg, msg: errorMsg });
return reject({ msg: errorMsg });
});
}
let apiUrl = '';
let apiUrlNoMsg = '';
if (flagOrUrl == 'flag') {
let apiFlag = argumentsArr[0];
if (typeof apiFlag === 'string') {
apiFlag = apiFlag || '';
apiUrl = apiFlag == '' ? '' : this.flagMap[apiFlag] || '';
}
apiUrlNoMsg = ' flag' + methodType + ':传入的标示 { ' + `${apiFlag}` + ' },未匹配到 apiUrl ';
}
if (flagOrUrl == 'url') {
apiUrl = argumentsArr[0];
if (typeof apiUrl === 'string') {
apiUrl = apiUrl || '';
}
apiUrlNoMsg = ' 未匹配到 apiUrl ';
}
if (apiUrl == '') {
return new Promise((resolve, reject) => {
this.resetNetError({ message: apiUrlNoMsg, msg: apiUrlNoMsg });
return reject({ message: apiUrlNoMsg, msg: apiUrlNoMsg });
});
}
// 如果传回一个
if (argNum == 1) {
return function (reqData) {
return _this.apiAll(methodType, apiUrl, reqData);
};
} else if (argNum == 2 || argNum == 3) {
let reqData = {};
let arg2Val = argumentsArr[1];
let arg2Type = Object.prototype.toString.call(arg2Val);
// let argType2_2 = typeof argumentsArr[1] === 'object';
if (arg2Type === '[object String]' || arg2Type === '[object Number]') {
// console.log('----转换-----', parseInt(arg2Val), Number(arg2Val));
var isEndId = Number(arg2Val);
if (!isNaN(isEndId)) {
// console.log('---数字');
if (!apiUrl.endsWith('/')) {
apiUrl = apiUrl + '/';
}
apiUrl = apiUrl + isEndId;
} else {
// console.log('---字符');
}
if (argNum == 3) {
let arg3Val = argumentsArr[2];
let arg3Type = Object.prototype.toString.call(arg3Val);
if (arg3Type === '[object Object]') {
reqData = arg3Val || {};
}
}
} else if (arg2Type === '[object Object]') {
reqData = arg2Val || {};
} else if (arg2Type === '[object FormData]') {
reqData = arg2Val || new FormData();
}
return _this.apiAll(methodType, apiUrl, reqData);
} else {
return new Promise((resolve, reject) => {
return reject({ msg: ' 请求错误 ' });
});
}
}
}
export default RequestClass;