增加公共请求方法配置

This commit is contained in:
YeMingfei666 2025-01-06 13:44:57 +08:00
parent f7364c7998
commit e0a55b8efe
9 changed files with 370 additions and 8 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
/node_modules/
/unpackage/

View File

@ -1 +1,4 @@
#new_app
#组件
components目录下符合目录规范如 components/my-test/my-test.vue
在页面中无需导入即可直接使用 my-test

46
commons/config.js Normal file
View File

@ -0,0 +1,46 @@
//打包时修改env的值即可
const env='test' //test , production,local
export const encryptKey='1234567890123456' // http数据加解密的key
export const apiUrl='/czg/'
export const h5Config = {
production: 'https://dj-h5.hnsiyao.cn',
test: 'https://web-api.hnsiyao.cn',
local: 'http://192.168.1.41:8100'
}
export const AppConfig = {
production: 'https://dj-api.hnsiyao.cn',
test: 'https://video-h5.hnsiyao.cn',
local: 'http://192.168.1.41:8100'
}
function returnShareUrl(){
if(env==='test'){
return 'https://video-h5.hnsiyao.cn'
}
if(env==='production'){
return 'https://dj-h5.hnsiyao.cn'
}
if(env==='local'){
return AppConfig[env]
}
}
// #ifdef H5
export default{
baseUrl:h5Config[env],
baseApiUrl:h5Config[env]+apiUrl,
shareUrl:returnShareUrl()
}
// #endif
// #ifdef APP
export default{
baseUrl:AppConfig[env],
baseApiUrl:AppConfig[env]+apiUrl,
shareUrl:returnShareUrl()
}
// #endif

177
http/http.js Normal file
View File

@ -0,0 +1,177 @@
// 导入全局属性
import {
sm4DecryptByResData
} from '@/utils/encryptUtil.js'
import infoBox from "@/utils/infoBox.js"
import { reject } from 'lodash';
import config from '@/commons/config.js'
// 测试服
let baseUrl = config.baseApiUrl
const loadingShowTime = 200
function getHeader(){
const headerObject={}
headerObject["token"] = uni.getStorageSync('token')
return headerObject
}
// 通用处理逻辑
function commonsProcess(showLoading, httpReqCallback) {
// 判断是否请求完成(用作 是否loading
// 包括: 'ing', 'ingLoading', 'finish'
let reqState = 'ing'
// 是否已经提示的错误信息
let isShowErrorToast = false
// 请求完成, 需要处理的动作
let reqFinishFunc = () => {
if (reqState == 'ingLoading') { // 关闭loading弹层
infoBox.hideLoading()
}
reqState = 'finish' // 请求完毕
}
// 明确显示loading
if (showLoading) {
// xx ms内响应完成不提示loading
setTimeout(() => {
if (reqState == 'ing') {
reqState = 'ingLoading'
infoBox.showLoading()
}
}, loadingShowTime)
}
return httpReqCallback().then((httpData) => {
reqFinishFunc(); // 请求完毕的动作
// 从http响应数据中解构响应数据 [ 响应码、 bodyData ]
let {
statusCode,
data
} = httpData
// 避免混淆重新命名
let bodyData = data
if (statusCode == 500) {
isShowErrorToast = true
return Promise.reject(bodyData) // 跳转到catch函数
}
if (statusCode == 401) {
// 提示信息
isShowErrorToast = true
return Promise.reject(bodyData) // 跳转到catch函数
}
// http响应码不正确
if (statusCode != 200 && statusCode != 204 && statusCode != 201) {
isShowErrorToast = true
data.message=data.message=='Bad credentials'?'用户名或密码错误':data.message
infoBox.showToast(data.message || '服务器异常')
return Promise.reject(bodyData) // 跳转到catch函数
}
// 加密数据
if (!bodyData.data && bodyData.encryptData) {
return Promise.resolve({
bizData: sm4DecryptByResData(bodyData.encryptData),
code: bodyData.code
})
}
// 构造请求成功的响应数据
return Promise.resolve(bodyData)
}).catch(res => {
if(res.status==401){
infoBox.showErrorToast(res.message||'请登录').then(() => {
uni.redirectTo({url: '/pages/login/index'})
reject()
})
}
if(res.status==500){
infoBox.showErrorToast(res.message||'服务器异常').then(() => {
})
}
reqFinishFunc(); // 请求完毕的动作
// 如果没有提示错误, 那么此处提示 异常。
if (!isShowErrorToast) {
infoBox.showErrorToast(`请求网络异常`)
}
return Promise.reject(res)
}).finally(() => { // finally 是 then结束后再执行, 此处不适用。 需要在请求完成后立马调用: reqFinishFunc()
});
}
// 默认 显示loading(控制 xxs 内 不提示loading )
function req(uri, data, method = "GET", showLoading = true, extParams = {}) {
return commonsProcess(showLoading, () => {
return uni.request(
Object.assign({
url: baseUrl + uri,
data: data,
method: method,
header: getHeader()
}, extParams)
)
})
}
// 默认 显示loading(控制 xxs 内 不提示loading )
function request(args) {
const {
url,
data,
params,
method = "GET",
showLoading = true,
extParams = {}
} = args
let headerObject = {}
return commonsProcess(showLoading, () => {
return uni.request(
Object.assign({
url: baseUrl + url,
data: params||data,
method: method,
header: getHeader()
}, extParams)
)
})
}
// 上传
function upload(uri, data, file, showLoading = true, extParams = {}) {
// 放置token
let headerObject = {}
return commonsProcess(showLoading, () => {
return uni.uploadFile(
Object.assign({
url: baseUrl + uri,
formData: data,
name: "file",
filePath: file.path||file.url,
header: getHeader()
}, extParams)
).then((httpData) => {
// uni.upload 返回bodyData 的是 string类型。 需要解析。
httpData.data = JSON.parse(httpData.data)
return Promise.resolve(httpData)
}).catch(err=>{
uni.hideLoading()
infoBox.showErrorToast(`上传失败`)
})
})
}
export default {
req: req,
request,
upload: upload
}

17
main.js
View File

@ -1,23 +1,26 @@
import App from './App'
import uviewPlus from 'uview-plus'
// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
import {
createSSRApp
} from 'vue'
export function createApp() {
const app = createSSRApp(App)
app.use(uviewPlus)
return {
app
}
const app = createSSRApp(App)
app.use(uviewPlus)
return {
app
}
}
// #endif

View File

@ -2,6 +2,10 @@
"dependencies": {
"clipboard": "^2.0.11",
"dayjs": "^1.11.13",
"gm-crypto": "^0.1.8",
"jsbn": "^1.1.0",
"lodash": "^4.17.21",
"to-arraybuffer": "^1.0.1",
"uview-plus": "^3.3.61"
}
}

View File

@ -1,7 +1,13 @@
<template>
</template>
<script>
<script setup>
import http from '@/http/http.js'
http.request({
url:'app/common/getAppUseKv'
}).then(res=>{
console.log(res);
})
</script>
<style>

64
utils/encryptUtil.js Normal file
View File

@ -0,0 +1,64 @@
import { SM4 } from 'gm-crypto'
import {encryptKey} from '@/commons/config.js'
let HEX_KEY = null
// 字符串转16进制
function str2hex(str) {
var val = ''
for (var i = 0; i < str.length; i++) {
if (val == '')
val = str.charCodeAt(i).toString(16)
else
val += str.charCodeAt(i).toString(16)
}
val += ''
return val
}
// 获取hex秘钥
function getHexKey(){
if(!HEX_KEY){
HEX_KEY = str2hex(encryptKey)
}
return HEX_KEY
}
// 解密 (http响应数据 做通用处理)
export function sm4DecryptByResData(data){
if(!data){
return data
}
let res = SM4.decrypt(data, getHexKey(), {
inputEncoding: 'base64',
outputEncoding: 'utf8'
})
if(!res){
return res
}
return JSON.parse(res)['originData']
}
// 加密 (http响应数据 做通用处理)
export function sm4EncryptByReqData(data){
if(!data){
return data
}
// 加密处理
let encryptData = SM4.encrypt(JSON.stringify(data), getHexKey(), {
inputEncoding: 'utf8',
outputEncoding: 'base64'
})
return {encryptData : encryptData}
}

58
utils/infoBox.js Normal file
View File

@ -0,0 +1,58 @@
/**
* 提示信息公共文件
*/
const model = {
// uni.showToast的封装
// 参数: 标题、 显示时长(单位: 秒) 扩展参数
// 返回: promise对象 当提示消失后调用 resolve()
showToast: (title, duration = 1.5, extObject) => {
return new Promise((resolve, reject) => {
uni.showToast(Object.assign({ title: title, icon: 'none', mask: false, duration: (duration * 1000) }, extObject))
setTimeout(resolve, (duration * 1000));
})
},
// success类型的提示
showSuccessToast: (title, duration) => {
return model.showToast(title, duration, {icon: 'success'})
},
// error类型的提示
showErrorToast: (title, duration) => {
return model.showToast(title, duration, {icon: 'error'})
},
showLoading: (title = '请稍后' ) => {
return uni.showLoading({ title: title, mask: true })
},
hideLoading: () => {
return uni.hideLoading()
},
// 返回 Promise 点击确定和取消
// APP安卓原生提示比较丑 APP 不推荐使用该函数 。
showModal: (title, confirmText = '确定', cancalText = '取消', extObject) => {
return new Promise((resolve, reject) => {
uni.showModal( Object.assign({
title: title,
confirmText: confirmText,
showCancel: cancalText ? true : false,
cancelText: cancalText,
success: function(r) {
if (r.confirm) {
resolve()
}else if (r.cancel) {
reject()
}
}
}, extObject ));
});
},
}
export default model