7caf72e2 by 张猛

请求优化

1 parent 7ef3fc22
...@@ -2,127 +2,165 @@ import config from '@/config.js' ...@@ -2,127 +2,165 @@ import config from '@/config.js'
2 import _ from 'underscore' 2 import _ from 'underscore'
3 3
4 const excludeUrls = ['getMemberCountInfo', 'getInfo'] 4 const excludeUrls = ['getMemberCountInfo', 'getInfo']
5 const SUCCESS_CODES = [0, 200]
6 const TOKEN_EXPIRE_CODES = [60001, 60002, 401]
7
8 // Loading计数器
9 let loadingCount = 0
5 10
6 // 获取Token 11 // 获取Token
7 function getToken() { 12 function getToken() {
8 try { 13 try {
9 const token = uni.getStorageSync('token') 14 return uni.getStorageSync('token') || ''
10 if (token) {
11 return token
12 } else {
13 return ''
14 }
15 } catch (e) { 15 } catch (e) {
16 console.log(e) 16 console.error('获取token失败:', e)
17 return ''
17 } 18 }
18 } 19 }
19 20
20 // 获取请求头 21 // 获取请求头
21 function getHeaders() { 22 function getHeaders() {
22 const token = getToken() 23 return {
23 const header = { 24 'Authorization': getToken(),
24 'Authorization': token, 25 'Content-Type': 'application/json',
25 'Content-Type': 'application/json', // 根据自己的数据类型
26 'Content-Language': 'zh_CN', 26 'Content-Language': 'zh_CN',
27 // "Content-Type":"application/x-www-form-urlencoded",
28 'Ztx-Per-Id': uni.getStorageSync('perId') || '-1' 27 'Ztx-Per-Id': uni.getStorageSync('perId') || '-1'
29 } 28 }
30 return header
31 } 29 }
32 30
33 const request = function (req) { 31 // 显示Loading
34 req.method = req.method.toUpperCase() 32 function showLoading(title = '加载中...') {
35 if (!['GET', 'POST', 'PUT', 'DELETE'].includes(req.method)) { 33 if (loadingCount == 0) {
36 uni.showToast({ 34 uni.showLoading({title, mask: true})
37 title: `暂不支持的请求方式: ${req.method}`, 35 }
38 icon: 'none' 36 loadingCount++
37 }
38
39 // 隐藏Loading
40 function hideLoading() {
41 loadingCount--
42 if (loadingCount == 0) {
43 uni.hideLoading()
44 }
45 }
46
47 // Token过期处理
48 function handleTokenExpire() {
49 // 清除本地存储
50 uni.removeStorageSync('token')
51 uni.removeStorageSync('perId')
52
53 // 跳转登录页
54 setTimeout(() => {
55 uni.redirectTo({
56 url: '/login/login'
39 }) 57 })
40 return 58 }, 1500)
59 }
60
61 // 显示错误提示
62 function showError(msg) {
63 uni.showToast({
64 title: msg || '请求失败',
65 icon: 'none',
66 duration: 2000
67 })
68 }
69
70 const request = function (req) {
71 // 参数校验
72 if (!req || !req.url) {
73 return Promise.reject(new Error('请求参数不完整'))
41 } 74 }
42 75
43 // if (req.method === 'GET') { 76 req.method = (req.method || 'GET').toUpperCase()
44 // if (!req.params) { 77 const validMethods = ['GET', 'POST', 'PUT', 'DELETE']
45 // req.params = {}
46 // }
47 // req.params.pageNum = req.params.pageNum || 1
48 // req.params.pageSize = req.params.pageSize || 50
49 // }
50 78
51 // if (req.method == 'POST' && !req.hideLoding) { 79 if (!validMethods.includes(req.method)) {
52 // uni.showLoading({ 80 const error = `暂不支持的请求方式: ${req.method}`
53 // title: '提交中...' 81 showError(error)
54 // }) 82 return Promise.reject(new Error(error))
55 // } 83 }
84
85 // 显示Loading
86 if (req.showLoading != false) {
87 showLoading(req.loadingTitle)
88 }
56 89
57 return new Promise((resolve, reject) => { 90 return new Promise((resolve, reject) => {
58 uni.request({ 91 uni.request({
59 url: config.baseUrl_api + req.url, 92 url: config.baseUrl_api + req.url,
60 method: req.method, 93 method: req.method,
61 data: req.params, 94 data: req.params,
62 header: getHeaders() 95 header: getHeaders(),
63 }).then(res => { 96 timeout: req.timeout || 60000 * 5 // 添加超时设置
64 switch (res.statusCode) { 97 }).then(response => {
65 case 200: 98 const {statusCode, data} = response
66 const data = res.data || {} 99
67 if (data.code === 0 || data.code === 200 || data.pageData?.code === 200) { 100 // HTTP状态码处理
68 resolve(data) 101 if (statusCode != 200) {
69 } else if (_.some(excludeUrls, (url) => req.url.indexOf(url) > -1)) { 102 throw new Error(`HTTP ${statusCode}`)
70 resolve(data) 103 }
71 } else { 104
72 // if (!excludeUrls.includes(req.url)) { 105 // 业务状态码处理
73 // if (data.msg) { 106 const isSuccess = SUCCESS_CODES.includes(data.code) ||
74 // uni.showModal({ 107 data.pageData?.code == 200 ||
75 // content: data.msg, 108 excludeUrls.some(url => req.url.includes(url))
76 // success: function(res) { 109
77 110 if (isSuccess) {
78 // } 111 resolve(data)
79 // }) 112 return
80 uni.showToast({
81 title: data.msg,
82 icon: 'none',
83 duration: 2000
84 })
85 // }
86 // uni.hideLoading()
87
88 // }
89
90 // 登录超时
91 // if (data.code === 60002 || data.code === 60001) {
92 // uni.redirectTo({
93 // url: '/login/login'
94 // })
95 // } else if (data.code === 401) {
96 // h5LoginAuto()
97 // .then(() => {
98 // uni.hideLoading()
99 // uni.redirectTo({
100 // url: getCurrentPages()[getCurrentPages()
101 // .length - 1].$page.fullPath
102 // })
103 // })
104 // .catch(() => {
105 // uni.showToast({
106 // title: '服务异常,请稍后重试',
107 // icon: 'none'
108 // })
109 // })
110 // }
111
112 reject(res)
113 }
114 break
115 default:
116 reject(res)
117 } 113 }
118 }).catch(res => { 114
119 reject(res) 115 // Token过期处理
116 if (TOKEN_EXPIRE_CODES.includes(data.code)) {
117 handleTokenExpire()
118 reject(new Error('登录已过期,请重新登录'))
119 return
120 }
121
122 // 其他业务错误
123 showError(data.msg || '请求失败')
124 reject(new Error(data.msg || '请求失败'))
125
126 }).catch(error => {
127 console.error('请求失败:', error)
128
129 // 网络错误处理
130 if (error.errMsg) {
131 if (error.errMsg.includes('timeout')) {
132 showError('请求超时,请稍后重试')
133 } else if (error.errMsg.includes('fail')) {
134 showError('网络连接失败')
135 } else {
136 showError('请求失败,请稍后重试')
137 }
138 }
139
140 reject(error)
120 }).finally(() => { 141 }).finally(() => {
121 // if (req.method == 'POST' && !req.hideLoading) { 142 if (req.showLoading != false) {
122 uni.hideLoading() 143 hideLoading()
123 // } 144 }
124 }) 145 })
125 }) 146 })
126 } 147 }
127 148
149 // 添加便捷方法
150 request.get = (url, params, options = {}) => {
151 return request({...options, url, method: 'GET', params})
152 }
153
154 request.post = (url, params, options = {}) => {
155 return request({...options, url, method: 'POST', params})
156 }
157
158 request.put = (url, params, options = {}) => {
159 return request({...options, url, method: 'PUT', params})
160 }
161
162 request.delete = (url, params, options = {}) => {
163 return request({...options, url, method: 'DELETE', params})
164 }
165
128 export default request 166 export default request
......
1 import config from '@/config.js'
2 import _ from 'underscore'
3
4 const excludeUrls = ['getMemberCountInfo', 'getInfo']
5 const SUCCESS_CODES = [0, 200]
6 const TOKEN_EXPIRE_CODES = [60001, 60002, 401]
7
8 // Loading计数器
9 let loadingCount = 0
10
11 // 获取Token
12 function getToken() {
13 try {
14 return uni.getStorageSync('token') || ''
15 } catch (e) {
16 console.error('获取token失败:', e)
17 return ''
18 }
19 }
20
21 // 获取请求头
22 function getHeaders() {
23 return {
24 'Authorization': getToken(),
25 'Content-Type': 'application/json',
26 'Content-Language': 'zh_CN',
27 'Ztx-Per-Id': uni.getStorageSync('perId') || '-1'
28 }
29 }
30
31 // 显示Loading
32 function showLoading(title = '加载中...') {
33 if (loadingCount === 0) {
34 uni.showLoading({title, mask: true})
35 }
36 loadingCount++
37 }
38
39 // 隐藏Loading
40 function hideLoading() {
41 loadingCount--
42 if (loadingCount === 0) {
43 uni.hideLoading()
44 }
45 }
46
47 // Token过期处理
48 function handleTokenExpire() {
49 // 清除本地存储
50 uni.removeStorageSync('token')
51 uni.removeStorageSync('perId')
52
53 // 跳转登录页
54 setTimeout(() => {
55 uni.redirectTo({
56 url: '/login/login'
57 })
58 }, 1500)
59 }
60
61 // 显示错误提示
62 function showError(msg) {
63 uni.showToast({
64 title: msg || '请求失败',
65 icon: 'none',
66 duration: 2000
67 })
68 }
69
70 const request = function (req) {
71 // 参数校验
72 if (!req || !req.url) {
73 return Promise.reject(new Error('请求参数不完整'))
74 }
75
76 req.method = (req.method || 'GET').toUpperCase()
77 const validMethods = ['GET', 'POST', 'PUT', 'DELETE']
78
79 if (!validMethods.includes(req.method)) {
80 const error = `暂不支持的请求方式: ${req.method}`
81 showError(error)
82 return Promise.reject(new Error(error))
83 }
84
85 // 显示Loading
86 if (req.showLoading !== false) {
87 showLoading(req.loadingTitle)
88 }
89
90 return new Promise((resolve, reject) => {
91 uni.request({
92 url: config.baseUrl_api + req.url,
93 method: req.method,
94 data: req.params,
95 header: getHeaders(),
96 timeout: req.timeout || 60000 // 添加超时设置
97 }).then(response => {
98 const {statusCode, data} = response
99
100 // HTTP状态码处理
101 if (statusCode !== 200) {
102 throw new Error(`HTTP ${statusCode}`)
103 }
104
105 // 业务状态码处理
106 const isSuccess = SUCCESS_CODES.includes(data.code) ||
107 data.pageData?.code === 200 ||
108 excludeUrls.some(url => req.url.includes(url))
109
110 if (isSuccess) {
111 resolve(data)
112 return
113 }
114
115 // Token过期处理
116 if (TOKEN_EXPIRE_CODES.includes(data.code)) {
117 handleTokenExpire()
118 reject(new Error('登录已过期,请重新登录'))
119 return
120 }
121
122 // 其他业务错误
123 showError(data.msg || '请求失败')
124 reject(new Error(data.msg || '请求失败'))
125
126 }).catch(error => {
127 console.error('请求失败:', error)
128
129 // 网络错误处理
130 if (error.errMsg) {
131 if (error.errMsg.includes('timeout')) {
132 showError('请求超时,请稍后重试')
133 } else if (error.errMsg.includes('fail')) {
134 showError('网络连接失败')
135 } else {
136 showError('请求失败,请稍后重试')
137 }
138 }
139
140 reject(error)
141 }).finally(() => {
142 if (req.showLoading !== false) {
143 hideLoading()
144 }
145 })
146 })
147 }
148
149 // 添加便捷方法
150 request.get = (url, params, options = {}) => {
151 return request({...options, url, method: 'GET', params})
152 }
153
154 request.post = (url, params, options = {}) => {
155 return request({...options, url, method: 'POST', params})
156 }
157
158 request.put = (url, params, options = {}) => {
159 return request({...options, url, method: 'PUT', params})
160 }
161
162 request.delete = (url, params, options = {}) => {
163 return request({...options, url, method: 'DELETE', params})
164 }
165
166 export default request
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!