当前位置:网站首页>封装 uniapp request 请求
封装 uniapp request 请求
2022-08-08 21:10:00 【前端开发工程师在杭州】
封装 uniapp request 请求
'use strict';
class Request {
config = {
debug: false,
baseurl: '',
encoding: 'utf-8',
content_type: 'json',
loading: 'nav-bar',
loading_duration: 0,
data: {
},
header: {
}
}
req_config = {
url: '',
data: {
},
header: {
},
method: 'GET',
timeout: 30000,
dataType: 'json',
responseType: 'text'
}
static isurl(url) {
return /(http|https):\/\/([\w.]+\/?)\S*/.test(url);
}
static geturl(config) {
return Request.isurl(config.url) ? (config.url || '') : (config.baseurl + config.url);
}
static get_content_type(config) {
switch (config.content_type){
case 'json':
return 'application/json';
case 'form':
return 'application/x-www-form-urlencoded';
case 'file':
return 'multipart/form-data';
case 'text':
return 'text/plain';
case 'html':
return 'text/html';
default:
throw new Error('content type error: ' + type);
}
}
/** * 拦截器 * */
interceptor = {
request: undefined,
response: undefined,
fail: undefined
}
/** * request 请求 * */
// 定义了一个默认参数
request(options = {
}) {
let that = this;
let config = Object.assign({
}, this.config, options);
config.url = Request.geturl(config);
if (!config.header['Content-Type']) {
config.header['Content-Type'] = Request.get_content_type(config);
}
if (typeof that.interceptor.request === 'function') {
config = that.interceptor.request(config);
}
let task = undefined
let promise = new Promise((resolve, reject) => {
let extras = {
}
that._prepare(that, config, extras)
if (config.content_type === 'file') {
task = uni.uploadFile({
...config,
success: res => {
that._success(that, config, res, resolve, reject)
},
fail: res => {
that._fail(that, config, res, resolve, reject)
},
complete: (res) => {
that._complete(that, config, res, extras)
}
})
if (typeof config.progress === 'function') {
task.onProgressUpdate(_res => {
config.progress(_res, task)
})
}
} else {
this._set_req_config(config);
task = uni.request({
...this.req_config,
success: res => {
that._success(that, config, res, resolve, reject)
},
fail: res => {
that._fail(that, config, res, resolve, reject)
},
complete: (res) => {
that._complete(that, config, res, extras)
}
})
}
})
if (config.success || config.fail || config.complete) {
return task;
}
return promise;
}
get(options = {
}) {
options.method = 'GET'
return this.request(options)
}
post(options = {
}) {
options.method = 'POST'
return this.request(options)
}
put(options = {
}) {
options.method = 'PUT'
return this.request(options)
}
delete(options = {
}) {
options.method = 'DELETE'
return this.request(options)
}
upload(options = {
}) {
options.method = 'POST'
options.content_type = 'file'
return this.request(options)
}
_success = function(that, config, res, resolve, reject) {
if (config.debug) {
console.log('response success res: ', res)
}
if (res.statusCode >= 200 && res.statusCode <= 302) {
let result = res.data
if (typeof result !== 'object') {
try{
result = JSON.parse(res.data);
}catch(e){
}
}
let is_success = !0;
if (typeof that.interceptor.response === 'function' && !config.skip_interceptor_response) {
is_success = that.interceptor.response(result, config)
}
if (is_success) {
if (config.debug) {
console.log('response success: ', result)
}
config.success ? config.success(result) : resolve(result)
return;
}
return;
}
that._fail(that, config, res, resolve, reject)
}
_fail = function(that, config, res, resolve, reject) {
if (config.debug) {
console.error('response failure: ', res)
}
if (res.errMsg === 'request:fail abort') {
return
}
if (typeof that.interceptor.fail === 'function') {
res = that.interceptor.fail(res, config)
}
config.fail ? config.fail(res) : reject(res)
}
_prepare = function(that, config, obj = {
}) {
obj.startTime = Date.now()
if (config.loading) {
if (config.loading === 'nav-bar') {
uni.showNavigationBarLoading();
} else {
uni.showLoading({
title: config.loading
})
}
}
if (config.content_type === 'file') {
if (config.formData === undefined || config.formData === null) {
config.formData = config.data
delete config.data
}
config.method = 'POST'
}
if (config.debug) {
console.log('request: ', config)
}
}
_complete = function(that, config, res, obj = {
}) {
obj.endTime = Date.now()
let diff = obj.endTime - obj.startTime;
if (config.debug) {
console.log('request completed in ' + (obj.endTime - obj.startTime) + ' ms')
}
if (config.loading) {
let duration = config.loading_duration || 0
if (diff < duration) {
diff = duration - diff
} else {
diff = 0
}
let __timer = setTimeout(function() {
if (config.loading === 'nav-bar') {
uni.hideNavigationBarLoading()
} else {
uni.hideLoading()
}
clearTimeout(__timer);
}, diff)
}
}
_set_req_config = function(config){
for(let key in this.req_config){
if (config.hasOwnProperty(key)){
this.req_config[key] = config[key]
}
}
}
}
export default new Request()
边栏推荐
- Everything原理探究以及C#实现
- 【JVM内存区域】
- [MEF] Chapter 04 MEF's Multi-Component Import (ImportMany) and Directory Services
- 小程序模拟淘宝京东商品轮播滑动展示功能模块
- GeoServer Getting Started Learning: 06-Publishing Multi-level TIF Map Data
- ESLint: The Function constructor is eval. (no-new-func)错误解决
- leetcode 217存在重复元素
- 回调、递归、闭包、构造函数
- pm2安装配置与基本命令你知道吗?
- 数组的push()、pop()、shift()和unshift()方法讲解
猜你喜欢
Getting Started with GeoServer: 04-Publishing Shapfile Map Data
第八章 继承
去噪论文 Beyond a Gaussian Denoiser: Residual Learning of Deep CNN for Image Denoising
Property or method “XXX“ is not defined on the instance but referenced during render.
360杜跃进ISC演讲:保障信创软件的可信性和安全性是信创安全体系的基础
4 Gephi
数组的push()、pop()、shift()和unshift()方法讲解
SIGIR 2022 | MCCLK: 一个用于知识感知推荐的多层次的交叉视图对比框架
C#实现Everything——UI与查询 附源码
MySQL无法启用/etc/my.cnf配置文件,重启报错Warning: World-writable config file ‘/etc/my.cnf’ is ignored的解决方法
随机推荐
常见的病毒(攻击)分类
sudo控制用户权限实战操作
一、Canvas应用的背景(个人理解)及基础语法
最简单的idea构建微服务模块
目标检测论文 Bridng the Gap Between Anchor-based and Anchor-free Detection via ATSS
GeoServer入门学习:07-发布多层级TIF地图大图数据
Under the Windows socket (TCP) console program
图像噪声水平估计INLE_paper
Property or method “XXX“ is not defined on the instance but referenced during render.
怎样在网上开户买股票比较安全?如何办理开户业务?
fastapi-后台任务、定时任务与消息队列
同一行div或者其他行间块状标签,垂直高度不一解决办法
[Method for converting timestamp to normal time format]
小程序-按钮透明无边框
drf-树形结构的model的序列化显示
fastapi-实战-综述
第十章 异常处理
回调、递归、闭包、构造函数
安装sentry
Bagging、Boosting、Stacking集成学习代码