wx.request()和 uni.request() 封装---通用模板

(ps:uni-app使用时,只需要将wx.request替换成uni.request 即可)

一、结构目录

request文件夹

config.js 配置文件

index.js 请求入口文件

二、config.js

export default{
    // 请求基础地址
	baseUrl:'',
	options:{
		 header:{"Content-type":"application/json"}
	},
	interceptor:{
		request:function(config){
            // 请求参数处理
			return config
		},
		response:function(response){
            // 响应数据处理
			return response
		}
	}
}

三、index.js

import config from './config.js'
// 默认请求数据的处理
function Http() {
	const {
		interceptor,
		options,
		baseUrl
	} = config
	this.interceptor = interceptor
	this.baseUrl = baseUrl
	this.options = Object.assign({}, {
		method: 'GET',
		data: {},
		header: {},
		success: function() {},
		fail: function() {},
		complete: function() {}
	}, options)
}
let task = null
Http.prototype.abort = function() {
	if (task) {
		task.abort()
	}
}

Http.prototype.request = function(options) {
	options.url = this.baseUrl + options.url
	const self = this

	return new Promise((resolve, reject) => {
		options.complete = function(response) {
			const statusCode = response.statusCode
			let newResponse = response
			if (typeof self.interceptor.response == 'function') {
				newResponse = self.interceptor.response(newResponse)
			}
			if (statusCode == 200) {
				resolve(newResponse)
			} else {
				reject(newResponse)
			}
		}
		let newOptions = Object.assign({}, self.options, options)
		if (typeof self.interceptor.request == 'function') {
			newOptions = self.interceptor.request(newOptions)
		}
		wx.request(newOptions)
	})

}

const https = new Http()
const requestMethod = ['get', 'post', 'put', "patch", 'head', 'options', 'delete']
const request = (options) => {
	if (typeof options == "string") {
		options = {
			url: options,
			method: "GET"
		};
	} else if (typeof options == "object") {
		options.method ? options.method.toUpperCase() : (options.method = "GET");
		if (options.method == "GET" && options.data) {
			options.params = {
				...options.data
			};
		}
	}
	return https.request(options);
};


requestMethod.forEach((method) => {
	request[method] = (url, data) => {
		return request({
			url,
			method: method.toLowerCase(),
			data,
		});
	};
});

export default request;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值