104 lines
2.6 KiB
JavaScript
104 lines
2.6 KiB
JavaScript
/**
|
||
* HTTP的封装, 基于uni.request
|
||
* 包括: 通用响应结果的处理 和 业务的增删改查函数
|
||
*
|
||
* @author terrfly
|
||
* @site https://www.jeequan.com
|
||
* @date 2021/12/16 18:35
|
||
*/
|
||
|
||
// 导入全局属性
|
||
import appConfig from "../config/appConfig.js"
|
||
import storageManage from "@/util/storageManage.js"
|
||
import { sm4DecryptByResData } from "@/util/encryptUtil.js"
|
||
|
||
function req(uri, data, method = "GET", extParams = {}) {
|
||
// 放置token
|
||
let headerObject = {}
|
||
headerObject[appConfig.tokenKey] = storageManage.token()
|
||
return uni
|
||
.request(
|
||
Object.assign(
|
||
{
|
||
url: appConfig.env.JEEPAY_BASE_URL + uri,
|
||
data: data,
|
||
method: method,
|
||
header: headerObject,
|
||
},
|
||
extParams
|
||
)
|
||
)
|
||
.then((httpData) => {
|
||
// 从http响应数据中解构响应数据 [ 响应码、 bodyData ]
|
||
let { statusCode, data } = httpData
|
||
// 避免混淆重新命名
|
||
let bodyData = data
|
||
if (statusCode == 401) {
|
||
uni.showToast({ title: "请登录1", icon: "none", mask: true, duration: 1500 })
|
||
setTimeout(function () {
|
||
uni.reLaunch({ url: "/pages/login/login" })
|
||
}, 1500)
|
||
}
|
||
// http响应码不正确
|
||
if (statusCode != 200) {
|
||
return Promise.reject(bodyData) // 跳转到catch函数
|
||
}
|
||
|
||
// 业务响应异常
|
||
if (bodyData.code != 0) {
|
||
uni.hideLoading()
|
||
uni.showToast({ icon: "none", title: bodyData.msg })
|
||
if (bodyData.code == 5005) {
|
||
// 密码已过期, 直接跳转到更改密码页面
|
||
uni.reLaunch({ url: "/pageWork/setUp/securitySetting/passwordSetting" })
|
||
}
|
||
return Promise.reject(bodyData.msg)
|
||
}
|
||
|
||
// 加密数据
|
||
if (!bodyData.data && bodyData.encryptData) {
|
||
return Promise.resolve({ bizData: sm4DecryptByResData(bodyData.encryptData), code: bodyData.code })
|
||
}
|
||
|
||
// 构造请求成功的响应数据
|
||
return Promise.resolve({ bizData: bodyData.data, code: bodyData.code })
|
||
})
|
||
.catch((res) => {
|
||
return Promise.reject(res)
|
||
})
|
||
}
|
||
|
||
// 通用list
|
||
function list(uri, params) {
|
||
return req(uri, params, "GET")
|
||
}
|
||
|
||
// 通用add
|
||
function add(uri, data) {
|
||
return req(uri, data, "POST")
|
||
}
|
||
|
||
// 通用 根据ID获取
|
||
function getById(uri, bizId) {
|
||
return req(`${uri}/${bizId}`, {}, "GET")
|
||
}
|
||
|
||
// 通用 更新
|
||
function updateById(uri, bizId, data) {
|
||
return req(`${uri}/${bizId}`, data, "PUT")
|
||
}
|
||
|
||
// 通用 删除
|
||
function delById(uri, bizId) {
|
||
return req(`${uri}/${bizId}`, {}, "DELETE")
|
||
}
|
||
|
||
export default {
|
||
req: req,
|
||
list: list,
|
||
add: add,
|
||
getById: getById,
|
||
updateById: updateById,
|
||
delById: delById,
|
||
}
|