111 lines
3.2 KiB
JavaScript
111 lines
3.2 KiB
JavaScript
import {
|
|
URL,
|
|
appid
|
|
} from './url'
|
|
|
|
// 获取多语言翻译文本
|
|
const getLoadingText = () => {
|
|
try {
|
|
const lang = uni.getStorageSync('language') || 'zh-CN'
|
|
return lang === 'en-US' ? 'Loading...' : '加载中...'
|
|
} catch (e) {
|
|
return '加载中...'
|
|
}
|
|
}
|
|
|
|
const request = (option) => {
|
|
return new Promise((resolve, reject) => {
|
|
|
|
// 默认不显示加载中提示
|
|
if (!option.hideLoading) {
|
|
uni.showLoading({
|
|
title: option.loadingText || getLoadingText(),
|
|
mask: true
|
|
})
|
|
}
|
|
|
|
uni.request({
|
|
url: URL + option.url,
|
|
method: option.method,
|
|
data: option.data,
|
|
header: {
|
|
"Content-Type": option.headers && option.headers["Content-Type"] ? option.headers["Content-Type"] : (option.method && option.method.toUpperCase() === 'POST' ? 'application/json' : 'application/x-www-form-urlencoded'),
|
|
...option.headers,
|
|
'appid': appid,
|
|
'Authorization': "Bearer " + uni.getStorageSync('token'),
|
|
'Clientid': uni.getStorageSync('client_id')
|
|
},
|
|
success(res) {
|
|
|
|
|
|
// 检查响应状态码
|
|
if (res.statusCode !== 200) {
|
|
console.error(`HTTP状态码错误: ${res.statusCode}`, res.data)
|
|
|
|
// 为了适应某些服务器的异常响应,我们仍然返回数据
|
|
if (res.data) {
|
|
resolve(res.data)
|
|
return
|
|
}
|
|
|
|
reject({msg: `请求失败,状态码:${res.statusCode}`})
|
|
return
|
|
}
|
|
|
|
// 未登录或 token 失效处理(支持多种后端返回)
|
|
if (res.statusCode === 401 || res.data?.code === 401 || res.data?.code === 40101) {
|
|
try {
|
|
// 清理本地登录态
|
|
uni.removeStorageSync('token')
|
|
// 计算重定向地址
|
|
const pages = getCurrentPages()
|
|
const current = pages && pages.length ? pages[pages.length - 1] : null
|
|
const route = current && current.route ? ('/' + current.route) : '/pages/index/index'
|
|
const query = current && current.options ? Object.keys(current.options).map(k => `${k}=${encodeURIComponent(current.options[k])}`).join('&') : ''
|
|
const redirect = encodeURIComponent(query ? `${route}?${query}` : route)
|
|
// 跳转到登录页
|
|
uni.reLaunch({ url: `/pages/login/index?redirect=${redirect}` })
|
|
} catch (e) {}
|
|
}
|
|
|
|
// 检查业务状态码
|
|
if (res.data && res.data.code !== 200) {
|
|
console.warn(`业务状态码错误: ${res.data.code}`, res.data)
|
|
|
|
// 判断是否需要忽略数据为空的错误
|
|
if (option.ignoreEmptyError &&
|
|
(res.data.code === 500 && res.data.msg &&
|
|
(res.data.msg.includes('未找到') || res.data.msg.includes('不存在')))) {
|
|
// 对于指定需要忽略的错误,返回一个标准的"成功但数据为空"的响应
|
|
resolve({
|
|
code: 200,
|
|
msg: "操作成功",
|
|
data: []
|
|
})
|
|
return
|
|
}
|
|
|
|
// 仍然返回数据,由业务逻辑处理
|
|
resolve(res.data)
|
|
return
|
|
}
|
|
|
|
resolve(res.data)
|
|
},
|
|
fail(err) {
|
|
// 网络请求本身失败
|
|
console.error(`请求失败: ${option.url}`, err)
|
|
reject(err)
|
|
},
|
|
complete() {
|
|
// 隐藏加载提示
|
|
if (!option.hideLoading) {
|
|
uni.hideLoading()
|
|
}
|
|
}
|
|
})
|
|
})
|
|
}
|
|
|
|
|
|
export default request |