You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
416 lines
13 KiB
416 lines
13 KiB
/** |
|
* 请求封装 |
|
*/ |
|
import $ from './globalJs' |
|
const tokenKey = 'token' |
|
const tokenKeyValue = '' |
|
|
|
class Request { |
|
constructor(config = {}) { |
|
this.config = {}; |
|
this.config.baseUrl = config.baseUrl? config.baseUrl: ''; |
|
this.config.dataType = config.dataType? config.dataType: 'json'; |
|
this.config.responseType = config.responseType? config.responseType: 'text'; |
|
this.config.header = config.header? config.header: {}; |
|
this.reqInterceptors = null; |
|
this.resInterceptors = null; |
|
this.interceptors = { |
|
request: fn => { |
|
this.reqInterceptors = fn; |
|
}, |
|
response: fn => { |
|
this.resInterceptors = fn; |
|
} |
|
} |
|
} |
|
setConfig(config = {}) { |
|
this.config = this._deepCopy(this._merge(this.config, config)); |
|
} |
|
// 请求封装 |
|
globalRequest(url,config, method,isForm = '') { |
|
const _this = this; |
|
let newConfig = this._deepCopy(this._merge(this.config, config)); |
|
let lastConfig = {}; |
|
if (this.reqInterceptors && typeof this.reqInterceptors === 'function') { |
|
let reqInterceptors = this.reqInterceptors(newConfig); |
|
if (!reqInterceptors && process.env.NODE_ENV === "development") { |
|
console.log('请求被拦截,此消息仅在开发环境显示。') |
|
return false; |
|
} else if (Object.prototype.toString.call(reqInterceptors) === "[object Promise]") { |
|
return reqInterceptors; |
|
} |
|
lastConfig = this._deepCopy(reqInterceptors); |
|
} else { |
|
lastConfig = this._deepCopy(newConfig); |
|
} |
|
let header = {} |
|
let tokenData = $.getData('token') |
|
if(tokenData){ |
|
header[tokenKey] = tokenKeyValue + tokenData |
|
} |
|
if(isForm){ |
|
header['content-type'] = 'application/x-www-form-urlencoded' |
|
} |
|
let fullUrl = this._formatUrl(lastConfig.baseUrl, url); |
|
if(url.indexOf('http') != -1){ |
|
fullUrl = url |
|
} |
|
return new Promise((resolve, reject) => { |
|
console.log(fullUrl) |
|
uni.request({ |
|
url: fullUrl, |
|
method:method, |
|
data: config, |
|
header: header, |
|
async complete(response) { |
|
let res = response; |
|
if (_this.resInterceptors && typeof _this.resInterceptors === 'function') { |
|
let resInterceptors = _this.resInterceptors(res); |
|
// console.log('resInterceptors-----------------',resInterceptors) |
|
if(resInterceptors.statusCode == 400 || resInterceptors.data.code == 403){ |
|
$.toast('登录信息已过期,请重新登录') |
|
// $.removeData('token') |
|
// setTimeout(() => { |
|
// $.openNew('/pages/logIn/logIn') |
|
// },1500) |
|
return |
|
} |
|
if (!resInterceptors && resInterceptors != '') { |
|
reject('返回值已被您拦截!'); |
|
return; |
|
} else if (Object.prototype.toString.call(resInterceptors) === "[object Promise]") { |
|
try { |
|
let promiseRes = await resInterceptors; |
|
resolve(promiseRes) |
|
} catch (error) { |
|
reject(error) |
|
} |
|
} else { |
|
res = resInterceptors; |
|
} |
|
} |
|
resolve(res.data); |
|
} |
|
}); |
|
}) |
|
} |
|
|
|
addFile(file,success, progress) { |
|
const _this = this; |
|
let newConfig = this._deepCopy(this._merge(this.config, {})); |
|
let lastConfig = {}; |
|
if (this.reqInterceptors && typeof this.reqInterceptors === 'function') { |
|
let reqInterceptors = this.reqInterceptors(newConfig); |
|
if (!reqInterceptors && process.env.NODE_ENV === "development") { |
|
console.log('请求被拦截,此消息仅在开发环境显示。') |
|
return false; |
|
} else if (Object.prototype.toString.call(reqInterceptors) === "[object Promise]") { |
|
return reqInterceptors; |
|
} |
|
lastConfig = this._deepCopy(reqInterceptors); |
|
} else { |
|
lastConfig = this._deepCopy(newConfig); |
|
} |
|
let fullUrl = this._formatUrl(lastConfig.baseUrl, $.imgUrl); |
|
let header = { |
|
// 'content-Type':'multipart/form-data' |
|
} |
|
return new Promise((resolve, reject) => { |
|
const UploadTask = uni.uploadFile({ |
|
url : fullUrl, |
|
filePath: file[0].path, |
|
header:header, |
|
name: $.fileImgKey, |
|
formData: {}, |
|
async complete(response) { |
|
let res = response; |
|
if (_this.resInterceptors && typeof _this.resInterceptors === 'function') { |
|
let resInterceptors = _this.resInterceptors(res); |
|
if (!resInterceptors && resInterceptors != '') { |
|
reject('返回值已被您拦截!'); |
|
return; |
|
} else if (Object.prototype.toString.call(resInterceptors) === "[object Promise]") { |
|
try { |
|
let promiseRes = await resInterceptors; |
|
resolve(promiseRes) |
|
} catch (error) { |
|
reject(error) |
|
} |
|
} else { |
|
res = resInterceptors; |
|
} |
|
} |
|
success(JSON.parse(res.data)); |
|
} |
|
}); |
|
// 监听上传进度 |
|
if (progress) { |
|
UploadTask.onProgressUpdate((res) => { |
|
progress(res.progress); |
|
}) |
|
} |
|
}) |
|
} |
|
|
|
// 上传图片 |
|
addImg(length = 1,success,progress,type = 1) { |
|
// 获取本地图片的路径 |
|
uni.chooseImage({ |
|
count: length, |
|
// original原图compressed压缩图 |
|
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有 |
|
// camera相机album相册 |
|
sourceType: ['album','camera'], // 可以指定来源是相册还是相机,默认二者都有 |
|
success: (res) => { |
|
// 显示上传动画 |
|
$.showLoading('图片上传中...'); |
|
var imgs; |
|
imgs = res.tempFilePaths |
|
// #ifdef H5 |
|
// 调用上传图片的函数 |
|
// 处理多选 |
|
// if (imgs.length > length) { |
|
// imgs = imgs.slice(0, length); |
|
// } |
|
this.fileImg(imgs, 0, success, progress,type); |
|
// #endif |
|
// #ifdef APP |
|
console.log('imgs',imgs) |
|
// 将新添加的图片添加到imgs_arr中 |
|
uni.compressImage({ |
|
src: imgs[0], |
|
quality: 60, // 仅对jpg有效 |
|
success: ress => { |
|
this.fileImg([ress.tempFilePath], 0, success, progress,type); |
|
}, |
|
fail: err => { |
|
$.hideLoading('图片上传中...'); |
|
}, |
|
complete: (msg) => { |
|
} |
|
}); |
|
// #endif |
|
}, |
|
complete: (err) => { |
|
}, |
|
|
|
}) |
|
} |
|
fileImg(imgs, index,success, progress,type) { |
|
const _this = this; |
|
let newConfig = this._deepCopy(this._merge(this.config, {})); |
|
let lastConfig = {}; |
|
if (this.reqInterceptors && typeof this.reqInterceptors === 'function') { |
|
let reqInterceptors = this.reqInterceptors(newConfig); |
|
if (!reqInterceptors && process.env.NODE_ENV === "development") { |
|
console.log('请求被拦截,此消息仅在开发环境显示。') |
|
return false; |
|
} else if (Object.prototype.toString.call(reqInterceptors) === "[object Promise]") { |
|
return reqInterceptors; |
|
} |
|
lastConfig = this._deepCopy(reqInterceptors); |
|
} else { |
|
lastConfig = this._deepCopy(newConfig); |
|
} |
|
let fullUrl = this._formatUrl(lastConfig.baseUrl, $.imgUrl); |
|
if(type == 2){ |
|
fullUrl = this._formatUrl(lastConfig.baseUrl, $.imgUserIdUrl) |
|
} |
|
let header = { |
|
token: $.getData('token') |
|
} |
|
// 如果数组长度大于下标,说明没有上传完 |
|
if (imgs.length > index) { |
|
var src = imgs[index]; |
|
return new Promise((resolve, reject) => { |
|
const UploadTask = uni.uploadFile({ |
|
url : fullUrl, |
|
filePath: src, |
|
header:header, |
|
name: $.fileImgKey, |
|
formData: {}, |
|
async complete(response) { |
|
let res = response; |
|
if (_this.resInterceptors && typeof _this.resInterceptors === 'function') { |
|
let resInterceptors = _this.resInterceptors(res); |
|
// console.log('resInterceptors',resInterceptors) |
|
let datasJSON = JSON.parse(resInterceptors.data) |
|
if(datasJSON.code == 1101){ |
|
|
|
} |
|
if (!resInterceptors && resInterceptors != '') { |
|
reject('返回值已被您拦截!'); |
|
return; |
|
} else if (Object.prototype.toString.call(resInterceptors) === "[object Promise]") { |
|
try { |
|
let promiseRes = await resInterceptors; |
|
resolve(promiseRes) |
|
} catch (error) { |
|
reject(error) |
|
} |
|
} else { |
|
res = resInterceptors; |
|
} |
|
} |
|
success(JSON.parse(res.data)); |
|
_this.fileImg(imgs, index+1, progress) |
|
} |
|
}); |
|
// 监听上传进度 |
|
if (progress) { |
|
UploadTask.onProgressUpdate((res) => { |
|
progress(res.progress); |
|
}) |
|
} |
|
}) |
|
// #ifdef H5 |
|
// 压缩 |
|
// lrz(src, { |
|
// quality: 0.7, |
|
// }).then((rst) => { // fieldName 为 formData 中多媒体的字段名 |
|
|
|
// }) |
|
// #endif |
|
// #ifdef APP-PLUS |
|
// #endif |
|
|
|
} else { |
|
$.hideLoading(); |
|
} |
|
} |
|
|
|
// 上传视频 |
|
addVideo(url, success, progress) { |
|
// 获取本地视频的路径 |
|
uni.chooseVideo({ |
|
sourceType: ['album', 'camera'], // 选择方式 |
|
success: (res) => { |
|
if (res.size > $.videoSize) { |
|
let size = parseInt($.videoSize / 1024000); |
|
$.toast("上传视频过大,大小请不要超过" + size + "M"); |
|
} else { |
|
// 显示上传动画 |
|
$.showLoading("视频上传中..."); |
|
// 调用上传视频的函数 |
|
this.fileVideo(res.tempFilePath,url,success,progress); |
|
} |
|
}, |
|
fail: (res) => { |
|
console.log(JSON.stringify(res)); |
|
}, |
|
}) |
|
} |
|
fileVideo(src, url,success, progress) { |
|
const _this = this; |
|
let newConfig = this._deepCopy(this._merge(this.config, {})); |
|
let lastConfig = {}; |
|
if (this.reqInterceptors && typeof this.reqInterceptors === 'function') { |
|
let reqInterceptors = this.reqInterceptors(newConfig); |
|
if (!reqInterceptors && process.env.NODE_ENV === "development") { |
|
console.log('请求被拦截,此消息仅在开发环境显示。') |
|
return false; |
|
} else if (Object.prototype.toString.call(reqInterceptors) === "[object Promise]") { |
|
return reqInterceptors; |
|
} |
|
lastConfig = this._deepCopy(reqInterceptors); |
|
} else { |
|
lastConfig = this._deepCopy(newConfig); |
|
} |
|
let fullUrl = this._formatUrl(lastConfig.baseUrl, $.imgUrl); |
|
//上传视频 |
|
return new Promise((resolve, reject) => { |
|
const UploadTask = uni.uploadFile({ |
|
url: fullUrl, |
|
filePath: src, |
|
name: $.fileVideoKey, |
|
async complete(response) { |
|
let res = response; |
|
if (_this.resInterceptors && typeof _this.resInterceptors === 'function') { |
|
let resInterceptors = _this.resInterceptors(res); |
|
// console.log('resInterceptors',resInterceptors) |
|
if (!resInterceptors && resInterceptors != '') { |
|
reject('返回值已被您拦截!'); |
|
return; |
|
} else if (Object.prototype.toString.call(resInterceptors) === "[object Promise]") { |
|
try { |
|
let promiseRes = await resInterceptors; |
|
resolve(promiseRes) |
|
} catch (error) { |
|
reject(error) |
|
} |
|
} else { |
|
res = resInterceptors; |
|
} |
|
} |
|
success(JSON.parse(res.data)); |
|
$.hideLoading(); |
|
}, |
|
success: (res) => { |
|
success(JSON.parse(res.data)); |
|
// 关闭上传动画 |
|
}, |
|
fail: (e) => { |
|
// 关闭上传动画 |
|
$.hideLoading(); |
|
$.toast("上传超时!"); |
|
}, |
|
}) |
|
// 监听上传进度 |
|
if (progress) { |
|
UploadTask.onProgressUpdate((res) => { |
|
progress(res.progress); |
|
}) |
|
} |
|
}) |
|
} |
|
|
|
_formatUrl(baseUrl, url) { |
|
if (!baseUrl) return url; |
|
let formatUrl = ''; |
|
const baseUrlEndsWithSlash = baseUrl.endsWith('/'); |
|
const urlStartsWithSlash = url.startsWith('/'); |
|
if (baseUrlEndsWithSlash && urlStartsWithSlash) { |
|
formatUrl = baseUrl + url.substring(1); |
|
} else if (baseUrlEndsWithSlash || urlStartsWithSlash) { |
|
formatUrl = baseUrl + url; |
|
} else { |
|
formatUrl = baseUrl + '/' + url; |
|
} |
|
return formatUrl; |
|
} |
|
_merge(oldConfig, newConfig) { |
|
let mergeConfig = this._deepCopy(oldConfig); |
|
if (!newConfig || !Object.keys(newConfig).length) return mergeConfig; |
|
for (let key in newConfig) { |
|
if (key !== 'header') { |
|
mergeConfig[key] = newConfig[key]; |
|
} else { |
|
if (Object.prototype.toString.call(newConfig[key]) === '[object Object]') { |
|
for (let headerKey in newConfig[key]) { |
|
mergeConfig[key][headerKey] = newConfig[key][headerKey]; |
|
} |
|
} |
|
} |
|
} |
|
return mergeConfig; |
|
} |
|
_deepCopy(obj) { |
|
let result = Array.isArray(obj) ? [] : {}; |
|
for (let key in obj) { |
|
if (obj.hasOwnProperty(key)) { |
|
if (typeof obj[key] === 'object') { |
|
result[key] = this._deepCopy(obj[key]); |
|
} else { |
|
result[key] = obj[key]; |
|
} |
|
} |
|
} |
|
return result; |
|
} |
|
} |
|
|
|
if (!global.$request) { |
|
global.$request = new Request(); |
|
} |
|
|
|
export default global.$request;
|
|
|