0%

Taro学习-文件上传&&request封装

一个合适的request,事关整个项目获取数据的流畅和全局的权限管理。

对request几个需求:

  1. 常规请求 get,post, 上传文件等
  2. 全局参数带入(域名,参数)
  3. 返回请求头保存
  4. 全局出错状态处理

直接贴代码了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
function checkHttpStatus(response) {
if (response.statusCode >= 200 && response.statusCode < 300) {
let data
if (typeof response.data !== 'object'){
data = JSON.parse(response.data)
}else {
data = response.data
}
if (!Config.noConsole) {
console.log(`${new Date().toLocaleString()}【接口响应:】`,data);
}
if (data.code !== 0) {
Taro.showToast({
title: `${data.msg}`,
icon: 'none',
mask: true,
});
return null
}
if (response.header.wxuid) {
setGlobalData('wxuid', response.header.wxuid)
Taro.setStorageSync('wxuid',response.header.wxuid)
}
if (response.header.wxcid) {
setGlobalData('wxcid', response.header.wxcid)
Taro.setStorageSync('wxcid',response.header.wxcid)
}
if (data.content&&data.content.openid){
setGlobalData('wxaid', data.content.openid)
Taro.setStorageSync('wxaid',data.content.openid)
}
return data
}
Taro.showToast({
title: `服务端异常,请稍后重试`,
icon: 'none',
mask: true,
});
}
export default function request(url, options) {
let wxaid = getGlobalData('wxaid') || ''
let wxuid = getGlobalData('wxuid') || ''
let wxcid = getGlobalData('wxcid') || ''
let newOptions = { ...options}
Tips.loading()
if (options && options.customType === 'formData'){
newOptions.header = {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
wxaid: wxaid,
wxuid: wxuid,
wxcid: wxcid,
...newOptions.header
};
return Taro.uploadFile({
url: Config.API_HOST + url,
...newOptions})
.then(checkHttpStatus)
.then(checkSuccess)
.catch(()=>{
Taro.showToast({
title: `服务端异常,请稍后重试`,
icon: 'none',
mask: true,
});
setTimeout(() => {
Tips.loaded()
}, 2000)
})
}else {
if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
newOptions.header = {
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8',
wxaid: wxaid,
wxuid: wxuid,
wxcid: wxcid,
...newOptions.header
};
} else {
newOptions.header = {
'Content-Type': 'json',
wxaid: wxaid,
wxuid: wxuid,
wxcid: wxcid,
...newOptions.header
}
}
return Taro.request({
url: Config.API_HOST + url,
...newOptions})
.then(checkHttpStatus)
.then(checkSuccess)
.catch(()=>{
Taro.showToast({
title: `服务端异常,请稍后重试`,
icon: 'none',
mask: true,
});
setTimeout(() => {
Tips.loaded()
}, 2000)
})
}
}