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.
shop-app/common/plugins/msbUniRequest.js

97 lines
2.8 KiB

3 years ago
/*
* @Author: ch
* @Date: 2022-03-17 16:36:59
* @LastEditors: ch
3 years ago
* @LastEditTime: 2022-04-07 10:10:16
3 years ago
* @Description: 针对uniapp request请求做了一次封装使用思维参考axios
*
*
* 方法
* method(option) 自定义请求同uni.request
* get(url, params, header) url 请求地址 params 请求参数
* header 请求头会针对当前请求头设置特定的请求头传了此参数request拦截器会失效
* post(url, data, header) 同上
* put(url, data, header) 同上
* delete(url, data, header) 同上
* use(hookName, callback) 注入hook拦截器 hookName 拦截器名request/response/error callback拦截器具体见拦截器说明
*
* 属性
* baseUrl 请求地址前缀
*
* 拦截器
* request 请求前拦截在这可统一设置请求头请求体等参数uni.request的第一个参数option都可以重置
* success 请求成功结果拦截
* error 请求错误拦截
*
* 示例
* const myReq = new MsbUniRequest();
* myReq.baseUrl = 'xxxx'
* myReq.use('request', (option)=>{
* // option 返回请求配置
* .....这里可以对option做一系列操作
* return option //最后返回一个正确的请求配置
* })
* myReq.use('success', (res)=>{
* //res 返回请求结果
* let newRes = ..... //这里可以对请求结果做统一处理
* return newRes
* })
*
* myReq.use('error', (error)=>{
* //error 返回错误结果
* let newError = ..... //这里可以对请求错误做统一处理
* return newError
* })
*/
class MsbUniRequest {
constructor (option){
this.baseUrl = '';
this.hook = {
request : null,
success : null,
error : null
}
}
method(option){
option.url = this.baseUrl + option.url;
if(this.hook.request && !option.header){
option = this.hook.request(option);
}
if(!option){
throw new Error('没有请求配置或是request拦截未做return');
}
3 years ago
if(option.constructor === Promise){
return option
}
3 years ago
return new Promise((resolve, reject)=>{
uni.request(option).then(res => {
const response = res[1];
if(response.statusCode >= 200 && response.statusCode < 400){
resolve(this.hook.success ? this.hook.success(response) : response);
return false;
}
reject(this.hook.error ? this.hook.error(response) : response);
3 years ago
}).catch(error => {
reject(this.hook.error ? this.hook.error(error) : error);
});
});
}
use(hookName, cb){
this.hook[hookName] = cb;
}
get(url, data, header){
return this.method({method : 'GET', url, data, header});
3 years ago
}
post(url, data, header){
return this.method({method : 'POST', url, data, header});
3 years ago
}
put(url, data, header){
return this.method({method : 'PUT', url, data, header});
3 years ago
}
delete(url, data, header){
return this.method({method : 'DELETE', url, data, header});
3 years ago
}
}
export default MsbUniRequest;