7caf72e2 by 张猛

请求优化

1 parent 7ef3fc22
......@@ -2,127 +2,165 @@ import config from '@/config.js'
import _ from 'underscore'
const excludeUrls = ['getMemberCountInfo', 'getInfo']
const SUCCESS_CODES = [0, 200]
const TOKEN_EXPIRE_CODES = [60001, 60002, 401]
// Loading计数器
let loadingCount = 0
// 获取Token
function getToken() {
try {
const token = uni.getStorageSync('token')
if (token) {
return token
} else {
return ''
}
return uni.getStorageSync('token') || ''
} catch (e) {
console.log(e)
console.error('获取token失败:', e)
return ''
}
}
// 获取请求头
function getHeaders() {
const token = getToken()
const header = {
'Authorization': token,
'Content-Type': 'application/json', // 根据自己的数据类型
return {
'Authorization': getToken(),
'Content-Type': 'application/json',
'Content-Language': 'zh_CN',
// "Content-Type":"application/x-www-form-urlencoded",
'Ztx-Per-Id': uni.getStorageSync('perId') || '-1'
}
return header
}
const request = function (req) {
req.method = req.method.toUpperCase()
if (!['GET', 'POST', 'PUT', 'DELETE'].includes(req.method)) {
uni.showToast({
title: `暂不支持的请求方式: ${req.method}`,
icon: 'none'
// 显示Loading
function showLoading(title = '加载中...') {
if (loadingCount == 0) {
uni.showLoading({title, mask: true})
}
loadingCount++
}
// 隐藏Loading
function hideLoading() {
loadingCount--
if (loadingCount == 0) {
uni.hideLoading()
}
}
// Token过期处理
function handleTokenExpire() {
// 清除本地存储
uni.removeStorageSync('token')
uni.removeStorageSync('perId')
// 跳转登录页
setTimeout(() => {
uni.redirectTo({
url: '/login/login'
})
return
}, 1500)
}
// 显示错误提示
function showError(msg) {
uni.showToast({
title: msg || '请求失败',
icon: 'none',
duration: 2000
})
}
const request = function (req) {
// 参数校验
if (!req || !req.url) {
return Promise.reject(new Error('请求参数不完整'))
}
// if (req.method === 'GET') {
// if (!req.params) {
// req.params = {}
// }
// req.params.pageNum = req.params.pageNum || 1
// req.params.pageSize = req.params.pageSize || 50
// }
req.method = (req.method || 'GET').toUpperCase()
const validMethods = ['GET', 'POST', 'PUT', 'DELETE']
// if (req.method == 'POST' && !req.hideLoding) {
// uni.showLoading({
// title: '提交中...'
// })
// }
if (!validMethods.includes(req.method)) {
const error = `暂不支持的请求方式: ${req.method}`
showError(error)
return Promise.reject(new Error(error))
}
// 显示Loading
if (req.showLoading != false) {
showLoading(req.loadingTitle)
}
return new Promise((resolve, reject) => {
uni.request({
url: config.baseUrl_api + req.url,
method: req.method,
data: req.params,
header: getHeaders()
}).then(res => {
switch (res.statusCode) {
case 200:
const data = res.data || {}
if (data.code === 0 || data.code === 200 || data.pageData?.code === 200) {
resolve(data)
} else if (_.some(excludeUrls, (url) => req.url.indexOf(url) > -1)) {
resolve(data)
} else {
// if (!excludeUrls.includes(req.url)) {
// if (data.msg) {
// uni.showModal({
// content: data.msg,
// success: function(res) {
// }
// })
uni.showToast({
title: data.msg,
icon: 'none',
duration: 2000
})
// }
// uni.hideLoading()
// }
// 登录超时
// if (data.code === 60002 || data.code === 60001) {
// uni.redirectTo({
// url: '/login/login'
// })
// } else if (data.code === 401) {
// h5LoginAuto()
// .then(() => {
// uni.hideLoading()
// uni.redirectTo({
// url: getCurrentPages()[getCurrentPages()
// .length - 1].$page.fullPath
// })
// })
// .catch(() => {
// uni.showToast({
// title: '服务异常,请稍后重试',
// icon: 'none'
// })
// })
// }
reject(res)
}
break
default:
reject(res)
header: getHeaders(),
timeout: req.timeout || 60000 * 5 // 添加超时设置
}).then(response => {
const {statusCode, data} = response
// HTTP状态码处理
if (statusCode != 200) {
throw new Error(`HTTP ${statusCode}`)
}
// 业务状态码处理
const isSuccess = SUCCESS_CODES.includes(data.code) ||
data.pageData?.code == 200 ||
excludeUrls.some(url => req.url.includes(url))
if (isSuccess) {
resolve(data)
return
}
}).catch(res => {
reject(res)
// Token过期处理
if (TOKEN_EXPIRE_CODES.includes(data.code)) {
handleTokenExpire()
reject(new Error('登录已过期,请重新登录'))
return
}
// 其他业务错误
showError(data.msg || '请求失败')
reject(new Error(data.msg || '请求失败'))
}).catch(error => {
console.error('请求失败:', error)
// 网络错误处理
if (error.errMsg) {
if (error.errMsg.includes('timeout')) {
showError('请求超时,请稍后重试')
} else if (error.errMsg.includes('fail')) {
showError('网络连接失败')
} else {
showError('请求失败,请稍后重试')
}
}
reject(error)
}).finally(() => {
// if (req.method == 'POST' && !req.hideLoading) {
uni.hideLoading()
// }
if (req.showLoading != false) {
hideLoading()
}
})
})
}
// 添加便捷方法
request.get = (url, params, options = {}) => {
return request({...options, url, method: 'GET', params})
}
request.post = (url, params, options = {}) => {
return request({...options, url, method: 'POST', params})
}
request.put = (url, params, options = {}) => {
return request({...options, url, method: 'PUT', params})
}
request.delete = (url, params, options = {}) => {
return request({...options, url, method: 'DELETE', params})
}
export default request
......
import config from '@/config.js'
import _ from 'underscore'
const excludeUrls = ['getMemberCountInfo', 'getInfo']
const SUCCESS_CODES = [0, 200]
const TOKEN_EXPIRE_CODES = [60001, 60002, 401]
// Loading计数器
let loadingCount = 0
// 获取Token
function getToken() {
try {
return uni.getStorageSync('token') || ''
} catch (e) {
console.error('获取token失败:', e)
return ''
}
}
// 获取请求头
function getHeaders() {
return {
'Authorization': getToken(),
'Content-Type': 'application/json',
'Content-Language': 'zh_CN',
'Ztx-Per-Id': uni.getStorageSync('perId') || '-1'
}
}
// 显示Loading
function showLoading(title = '加载中...') {
if (loadingCount === 0) {
uni.showLoading({title, mask: true})
}
loadingCount++
}
// 隐藏Loading
function hideLoading() {
loadingCount--
if (loadingCount === 0) {
uni.hideLoading()
}
}
// Token过期处理
function handleTokenExpire() {
// 清除本地存储
uni.removeStorageSync('token')
uni.removeStorageSync('perId')
// 跳转登录页
setTimeout(() => {
uni.redirectTo({
url: '/login/login'
})
}, 1500)
}
// 显示错误提示
function showError(msg) {
uni.showToast({
title: msg || '请求失败',
icon: 'none',
duration: 2000
})
}
const request = function (req) {
// 参数校验
if (!req || !req.url) {
return Promise.reject(new Error('请求参数不完整'))
}
req.method = (req.method || 'GET').toUpperCase()
const validMethods = ['GET', 'POST', 'PUT', 'DELETE']
if (!validMethods.includes(req.method)) {
const error = `暂不支持的请求方式: ${req.method}`
showError(error)
return Promise.reject(new Error(error))
}
// 显示Loading
if (req.showLoading !== false) {
showLoading(req.loadingTitle)
}
return new Promise((resolve, reject) => {
uni.request({
url: config.baseUrl_api + req.url,
method: req.method,
data: req.params,
header: getHeaders(),
timeout: req.timeout || 60000 // 添加超时设置
}).then(response => {
const {statusCode, data} = response
// HTTP状态码处理
if (statusCode !== 200) {
throw new Error(`HTTP ${statusCode}`)
}
// 业务状态码处理
const isSuccess = SUCCESS_CODES.includes(data.code) ||
data.pageData?.code === 200 ||
excludeUrls.some(url => req.url.includes(url))
if (isSuccess) {
resolve(data)
return
}
// Token过期处理
if (TOKEN_EXPIRE_CODES.includes(data.code)) {
handleTokenExpire()
reject(new Error('登录已过期,请重新登录'))
return
}
// 其他业务错误
showError(data.msg || '请求失败')
reject(new Error(data.msg || '请求失败'))
}).catch(error => {
console.error('请求失败:', error)
// 网络错误处理
if (error.errMsg) {
if (error.errMsg.includes('timeout')) {
showError('请求超时,请稍后重试')
} else if (error.errMsg.includes('fail')) {
showError('网络连接失败')
} else {
showError('请求失败,请稍后重试')
}
}
reject(error)
}).finally(() => {
if (req.showLoading !== false) {
hideLoading()
}
})
})
}
// 添加便捷方法
request.get = (url, params, options = {}) => {
return request({...options, url, method: 'GET', params})
}
request.post = (url, params, options = {}) => {
return request({...options, url, method: 'POST', params})
}
request.put = (url, params, options = {}) => {
return request({...options, url, method: 'PUT', params})
}
request.delete = (url, params, options = {}) => {
return request({...options, url, method: 'DELETE', params})
}
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!