From 433de9c90622882a2941d8626f76301cb534ff4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?ZR20090193-=E9=99=88=E6=95=AC=E5=8B=87?= Date: Tue, 22 Nov 2022 09:43:35 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0401=E8=B7=B3=E8=BD=AC?= =?UTF-8?q?=E9=87=8D=E6=96=B0=E7=99=BB=E5=BD=95=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/DropBox/common/httpRequest.js | 132 ++++++++++++------------- app/DropBox/common/uni_request.js | 158 ++++++++++++++++++++++++++++++ app/DropBox/manifest.json | 2 +- 3 files changed, 225 insertions(+), 67 deletions(-) create mode 100644 app/DropBox/common/uni_request.js diff --git a/app/DropBox/common/httpRequest.js b/app/DropBox/common/httpRequest.js index 0e147a7..22dbda4 100644 --- a/app/DropBox/common/httpRequest.js +++ b/app/DropBox/common/httpRequest.js @@ -2,6 +2,7 @@ * 常用方法封装 请求,文件上传等 * @author echo. **/ +import uni_request from './uni_request.js' const tui = { //接口地址 interfaceUrl: function() { @@ -72,79 +73,59 @@ const tui = { * false:显示 */ request: function(url, method, postData, isDelay, isForm, hideLoading) { - //接口请求 - // let loadding = false; - // tui.delayed && uni.hideLoading(); - // clearTimeout(tui.delayed); - // tui.delayed = null; - // if (!hideLoading) { - // tui.delayed = setTimeout(() => { - // uni.showLoading({ - // mask: true, - // title: '请稍候...', - // success(res) { - // loadding = true - // } - // }) - // }, isDelay ? 1000 : 0) - // } - return new Promise((resolve, reject) => { uni.showLoading() - // // 追加统一请求参数 - // const tempdata = { - // UserId: uni.getStorageSync("UserId"), - // } - // // console.log('统一数据',tempdata) - // Object.assign(postData, tempdata) - // console.log('请求数据',postData) - // console.log('请求加密数据',Encrypt.Encrypt(JSON.stringify(postData))) - var inurl = tui.interfaceUrl() + url; - console.log('请求地址', inurl) + var inurl = tui.interfaceUrl() + url; // console.log("token",tui.getToken()) + let token = tui.getToken() + uni.request({ - url: inurl, - // data: { - // ReqSign: Encrypt.Encrypt(JSON.stringify(postData)), - // }, - data: postData, - header: { - 'content-type': isForm ? 'application/x-www-form-urlencoded' : - 'application/json', - 'Authorization': 'Bearer ' + tui.getToken() - }, - method: method, //'GET','POST' - dataType: 'json', - success: (res) => { - uni.hideLoading() - console.log('返回数据',res) - // console.log('返回数据0',res.data) - // console.log('返回数据1',Encrypt.Decrypt(res.data)) - // var result = JSON.parse(Encrypt.Decrypt(res.data)).ResSign - // var result = JSON.parse(res.data) - // resolve(JSON.parse(result)) - // console.log('解密数据',result) - if (res.statusCode === 401) { - // uni.reLaunch({ - // url: 'pages/login/login' - // }) - uni.clearStorage() - uni.reLaunch({ - url: 'pages/index/index' - }) - } else { - resolve(res.data) - } - }, - fail: (res) => { - console.log('fail返回数据', res) - uni.hideLoading() - reject(res) - }, + url: inurl, + data: postData, + header: { + 'content-type': isForm ? 'application/x-www-form-urlencoded' : + 'application/json', + 'Authorization': 'Bearer ' + tui.getToken() + }, + method: method, //'GET','POST' + dataType: 'json', + // success: (res) => { + // uni.hideLoading() + // console.log('返回数据',res) + // let errorMsg = '登录超时'; + // if (res.statusCode === 401) { + // uni.clearStorage() + // reject(errorMsg); + // } else { + // resolve(res.data) + // } + // }, + // fail: (res) => { + // console.log('fail返回数据', res) + // uni.hideLoading() + // reject(res) + // }, - }) + }) + .then((result)=>{ + let [error,res] = result; + console.log(result) + uni.hideLoading() + if(res.statusCode === 200){ + resolve(res.data) + } + if(res.statusCode === 401){ + uni.clearStorage() + // Promise.reject(new Error('token失效')); + uni.reLaunch({ url: '/pages/login/login' }); + } + }) + // .then(res => interceptorsRes(res, resolve, reject)) + .catch(err => interceptorsErr(err, reject)) }) }, + + /** * 上传文件 * @param string url 请求地址 @@ -219,5 +200,24 @@ const tui = { } } } +// 响应拦截 +const interceptorsRes = (res, resolve, reject) => { + console.log(res) + // const { + // code + // } = resp.data + // if (code == 200) { + // console.log("请求成功") + // } + // if (code == 401) { + // console.log("未授权,跳转回登录页") + // } + resolve(res) +} +// 异常处理 +const interceptorsErr = (err, reject) => { + console.log("网络异常", err) + reject(err) +} export default tui diff --git a/app/DropBox/common/uni_request.js b/app/DropBox/common/uni_request.js new file mode 100644 index 0000000..fc4588c --- /dev/null +++ b/app/DropBox/common/uni_request.js @@ -0,0 +1,158 @@ +export default function ({ baseURL, timeout = 56 * 1000, header: headers, statusCode = [200, 401] }) { + return { + get(url, data, header, ...args) { return this.request('GET', url, data, { ...header, ...headers }, ...args) }, + post(url, data, header, ...args) { return this.request('POST', url, data, { ...header, ...headers }, ...args) }, + put(url, data, header, ...args) { return this.request('PUT', url, data, { ...header, ...headers }, ...args) }, + delete(url, data, header, ...args) { return this.request('DELETE', url, data, { ...header, ...headers }, ...args) }, + connect(url, data, header, ...args) { return this.request('CONNECT', url, data, { ...header, ...headers }, ...args) }, + head(url, data, header, ...args) { return this.request('HEAD', url, data, { ...header, ...headers }, ...args) }, + options(url, data, header, ...args) { return this.request('OPTIONS', url, data, { ...header, ...headers }, ...args) }, + reace(url, data, header, ...args) { return this.request('TRACE', url, data, { ...header, ...headers }, ...args) }, + uploadFile(url, data, header, ...args) { return this.file('uploadFile', url, data || {}, { ...header, ...headers }, ...args) }, + downloadFile(url, data, header, ...args) { return this.file('downloadFile', url, data || {}, { ...header, ...headers }, ...args) }, + onerror: () => {}, // 请求错误钩子函数集合 + file(method, url, data, header, reqIntercept, resIntercept) { + let timer, // timer 检测超时定时器 + requestTask, // requestTask 网络请求 task 对象 + aborted = false, // aborted 请求是否已被取消 + overtime = false, // overtime 请求是否超时 + abort = () => { // abort 取消请求方法 + aborted = true // 将请求状态标记为已取消 + requestTask ? requestTask.abort() : '' // 执行取消请求方法 + }, + progressUpdateHandle, + onProgressUpdate = e => progressUpdateHandle = e // progressUpdateHandle 监听上传进度变化回调,onProgressUpdate 监听上传进度变化方法 + return new Proxy(new Promise((resolve, reject) => { // 返回经过 Proxy 后的 Promise 对象使其可以监听到是否调用 abort 和 onProgressUpdate 方法 + this.interceptors.request.intercept({ header: header || {}, body: data.formData || {} }, method, url, data, reqIntercept).then(async ({ header, body, cancel }) => { // 等待请求拦截器里的方法执行完 + if (aborted || cancel) { // 如果请求已被取消,停止执行,返回 reject + await this.onerror(method, url, data, '网络请求失败:主动取消') + return reject('网络请求失败:主动取消') + } + requestTask = uni[method]({ + url: url[0] === '/' ? baseURL + url : url, + name: data.name, + header, + filePath: data.filePath, + formData: body, + success: async res => { + clearTimeout(timer) + !statusCode.includes(res.statusCode) ? await this.onerror(method, url, data, `网络请求异常:服务器响应异常:状态码:${res.statusCode}`) : '', + this.interceptors.response.intercept(statusCode.includes(res.statusCode) ? resolve : reject, { + success: statusCode.includes(res.statusCode), ...res, + }, method, url, data, reject, resIntercept) // 执行响应拦截器 + }, + fail: async res => { + clearTimeout(timer) + !overtime && await this.onerror(method, url, data, aborted ? '网络请求失败:主动取消' : '网络请求失败:(URL无效|无网络|DNS解析失败)') + aborted ? reject('网络请求失败:主动取消') : reject('网络请求失败:(URL无效|无网络|DNS解析失败)') + } + }) + requestTask.onProgressUpdate(progressUpdateHandle) // 监听下载进度变化 + timer = setTimeout(async () => { // 请求超时执行方法 + overtime = true // 将状态标记为超时,不会被 fail 中的 onerror 重复执行 + requestTask.abort() // 执行取消请求方法 + await this.onerror(method, url, data, '网络请求失败:超时取消') + reject('网络请求时间超时') // reject 原因 + }, timeout) // 设定检测超时定时器 + }) + }), { get: (target, prop) => { + if (prop === 'abort') { + return abort + } else { + if (Reflect.get(target, prop) && Reflect.get(target, prop).bind) { + return Reflect.get(target, prop).bind(target) + } else { + return Reflect.get(target, prop) + } + } + } }) // 如果调用 cancel 方法,返回 _watcher.cancel 方法 + }, + request(method, url, data, header, reqIntercept, resIntercept) { + let timer, // timer 检测超时定时器 + requestTask, // requestTask 网络请求 task 对象 + aborted = false, // aborted 请求是否已被取消 + overtime = false, // overtime 请求是否超时 + abort = () => { // timer 检测超时定时器,requestTask 网络请求 task 对象,aborted 请求是否已被取消,abort 取消请求方法 + aborted = true // 将请求状态标记为已取消 + requestTask ? requestTask.abort() : '' // 执行取消请求方法 + } + return new Proxy(new Promise((resolve, reject) => { // 返回经过 Proxy 后的 Promise 对象使其可以监听到是否调用 abort 方法 + this.interceptors.request.intercept({ header: header || {}, body: data || {} }, method, url, data, reqIntercept).then(async ({ header, body: data, cancel }) => { // 等待请求拦截器里的方法执行完 + if (aborted || cancel) { // 如果请求已被取消,停止执行,返回 reject + await this.onerror(method, url, data, '网络请求失败:主动取消') + return reject('网络请求失败:主动取消') + } + requestTask = uni.request({ + url: url[0] === '/' ? baseURL + url : url, + data, method, header, + success: async res => { // 网络请求成功 + clearTimeout(timer) // 清除检测超时定时器 + !statusCode.includes(res.statusCode) ? await this.onerror(method, url, data, `网络请求异常:服务器响应异常:状态码:${res.statusCode}`) : '' + this.interceptors.response.intercept(statusCode.includes(res.statusCode) ? resolve : reject, { + success: statusCode.includes(res.statusCode), ...res, + }, method, url, data, reject, resIntercept) // 执行响应拦截器 + }, + fail: async res => { // 网络请求失败 + clearTimeout(timer) // 清除检测超时定时器 + !overtime && await this.onerror(method, url, data, aborted ? '网络请求失败:主动取消' : '网络请求失败:(URL无效|无网络|DNS解析失败)') + aborted ? reject('网络请求失败:主动取消') : reject('网络请求失败:(URL无效|无网络|DNS解析失败)') + } + }) + timer = setTimeout(async () => { // 请求超时执行方法 + overtime = true // 将状态标记为超时,不会被 fail 中的 onerror 重复执行 + requestTask.abort() // 执行取消请求方法 + await this.onerror(method, url, data, '网络请求失败:超时取消') + reject('网络请求时间超时') // reject 原因 + }, timeout || 12345) // 设定检测超时定时器 + }) + }), { + get: (target, prop) => { + if (prop === 'abort') { + return abort + } else { + if (Reflect.get(target, prop) && Reflect.get(target, prop).bind) { + return Reflect.get(target, prop).bind(target) + } else { + return Reflect.get(target, prop) + } + } + } + }) // 如果调用 abort 方法,返回 abort 方法 + }, + interceptors: { // 拦截器 + request: { + interceptors: [], + use(fun) { this.interceptors.push(fun) }, + async intercept(config, method, url, data, reqIntercept) { + if (!reqIntercept) { // 如果请求允许被拦截 + for (let i = 0; i < this.interceptors.length; i ++) { + config = await this.interceptors[i](config, method, url, data) + } + } + return config + } + }, + response: { + interceptors: [], + use(fun) { this.interceptors.push(fun) }, + async intercept(STATUS, response, method, url, data, reject, resIntercept) { + try{ + if (!resIntercept) { // 如果请求允许被拦截 + for (let i = 0; i < this.interceptors.length; i ++) { + response = await this.interceptors[i](response, method, url, data) + } + } + if (response.success) { + return STATUS(typeof response.data === 'string' ? JSON.parse(response.data) : response.data) + } else { + delete response.success + return STATUS(response, method, url, data) + } + }catch(e){ + reject(e) + } + } + } + } + } +} diff --git a/app/DropBox/manifest.json b/app/DropBox/manifest.json index a53cf43..9bd0060 100644 --- a/app/DropBox/manifest.json +++ b/app/DropBox/manifest.json @@ -2,7 +2,7 @@ "name" : "落箱App", "appid" : "__UNI__032F53F", "description" : "", - "versionName" : "1.2.0", + "versionName" : "1.3.0", "versionCode" : "100", "transformPx" : false, /* 5+App特有相关 */