This commit is contained in:
zpc 2025-07-22 23:01:06 +08:00
parent 2bd2293384
commit af8feb3fe7
11 changed files with 354 additions and 39 deletions

30
common/env.js Normal file
View File

@ -0,0 +1,30 @@
/**
* 项目环境配置文件
* 集中管理所有环境相关的配置参数
*/
// 开发环境配置
const development = {
// API基础URL
// baseUrl: 'https://ydsapi.zpc-xy.com',
baseUrl: 'http://localhost:2015',
imageUrl: 'https://guyu-1308826010.cos.ap-shanghai.myqcloud.com',
};
// 生产环境配置
const production = {
baseUrl: 'https://ydsapi.zpc-xy.com',
imageUrl: 'https://guyu-1308826010.cos.ap-shanghai.myqcloud.com',
};
// 根据环境变量选择对应配置
let currentEnv = development;//production;//testing;
// 衍生配置
const config = {
...currentEnv,
apiBaseUrl: currentEnv.baseUrl + '/api/',
};
export default config;

8
common/server/config.js Normal file
View File

@ -0,0 +1,8 @@
import request from '@/common/system/request';
export const getConfig = async () => {
let res = await request.get('Common/GetConfigV3', {});
return res.data;
}

View File

@ -0,0 +1,66 @@
/**
* 设置缓存,持久化到本地
* @param {String} key 缓存key
* @param {Object} value 缓存数据
*/
export const setCache = (key, value) => {
uni.setStorageSync(key, value);
}
/**
* 获取缓存
* @param {String} key 缓存key
* @returns {Object} 缓存数据
*/
export const getCache = (key) => {
return uni.getStorageSync(key);
}
/**
* 删除缓存
* @param {String} key 缓存key
*/
export const removeCache = (key) => {
uni.removeStorageSync(key);
}
/**
* 本地缓存
*/
let localCache = {};
/**
* 设置缓存非持久化
* @param {String} key 缓存key
* @param {Object} value 缓存数据
* @param {Number} time 缓存时间
*/
export const setLocalStorage = (key, value, time = 0) => {
localCache[key] = {
value: value,
expireTime: time > 0 ? Date.now() + time * 1000 : 0,
createTime: Date.now()
}
}
/**
* 获取缓存非持久化
* @param {String} key 缓存key
* @returns {Object} 缓存数据
*/
export const getLocalStorage = (key) => {
if (localCache[key]) {
if (localCache[key].expireTime > 0 && localCache[key].expireTime > Date.now()) {
return localCache[key].value;
}
}
return null;
}
/**
* 删除缓存非持久化
* @param {String} key 缓存key
*/
export const removeLocalStorage = (key) => {
delete localCache[key];
}

204
common/system/request.js Normal file
View File

@ -0,0 +1,204 @@
/**
* 网络请求工具类
* 封装统一的网络请求方法
*/
import EnvConfig from '@/common/env.js';
import md5 from 'js-md5';
import { getLocalStorage, setLocalStorage } from './cacheService';
import qs from 'qs';
class request {
/**
* 生成唯一的nonce值
* @returns {String} nonce值
*/
static generateNonce() {
return md5(Date.now() + Math.random().toString(36).substring(2, 15));
}
/**
* 创建签名
* @param {Object} data 请求数据
* @param {String} host 主机名
* @returns {Object} 带签名的数据和参数字符串
* @private
*/
static _createSignature(data, host) {
// 添加时间戳
data.timestamp = Math.floor(Date.now() / 1000);
// 添加nonce随机字符串
data.nonce = request.generateNonce();
// 按照键名对参数进行排序
const sortedParams = {};
Object.keys(data).sort().forEach(key => {
sortedParams[key] = data[key];
});
// 组合参数为字符串
let signStr = '';
for (const key in sortedParams) {
if (typeof sortedParams[key] === 'object') {
signStr += key + '=' + JSON.stringify(sortedParams[key]) + '&';
} else {
signStr += key + '=' + sortedParams[key] + '&';
}
}
// 获取时间戳,组合为密钥
const timestamp = data.timestamp;
const appSecret = host + timestamp;
// 添加密钥并去除最后的&
signStr = signStr.substring(0, signStr.length - 1) + appSecret;
// 使用MD5生成签名
const sign = md5(signStr);
data.sign = sign;
return { data, signStr };
}
/**
* 构建请求URL
* @param {String} url 请求路径
* @returns {Object} 包含请求URL和主机名的对象
* @private
*/
static _buildRequestUrl(url) {
let requestUrl = '';
if (url.startsWith('http://') || url.startsWith('https://')) {
// 如果是完整的URL直接使用
requestUrl = url;
} else {
// 否则拼接基础URL和相对路径
// 确保基础URL以/结尾,而请求路径不以/开头
const apiBaseUrl = EnvConfig.apiBaseUrl;
const baseUrlWithSlash = apiBaseUrl.endsWith('/') ? apiBaseUrl : apiBaseUrl + '/';
let routeMap = url;
const path = routeMap.startsWith('/') ? routeMap.substring(1) : routeMap;
requestUrl = baseUrlWithSlash + path;
}
// 使用正则表达式从URL中提取主机名
const hostRegex = /^(?:https?:\/\/)?([^\/]+)/i;
const matches = requestUrl.match(hostRegex);
const host = matches && matches[1] ? matches[1] : 'localhost';
return { requestUrl, host };
}
/**
* 发送请求
* @param {String} url 请求地址
* @param {Object} fromData 请求数据
* @param {String} method 请求方式
* @param {Boolean} showLoading 是否显示加载提示
* @returns {Promise} 返回请求Promise
*/
static request(url, fromData = {}, method = 'POST', showLoading = false) {
return new Promise((resolve, reject) => {
// 使用传入的method而不是重新声明
const requestMethod = method.toUpperCase();
const token = uni.getStorageSync('token');
let data = { ...fromData }; // 创建数据的深拷贝,避免修改原数据
// 构建请求URL和提取主机名
const { requestUrl, host } = request._buildRequestUrl(url);
// 显示加载提示
if (showLoading) {
uni.showLoading({
title: '正在加载中...',
mask: true
});
}
// 创建签名并准备请求数据和头信息
const { data: signedData } = request._createSignature(data, host);
data = signedData;
// 根据请求方法设置不同的headers
const header = {
Authorization: 'Bearer ' + token,
'content-type': 'application/json'
};
const startDate = Date.now();
// 发起网络请求
uni.request({
url: requestUrl,
method: requestMethod,
header: header,
data: data,
timeout: 30000, // 设置30秒超时
success: res => {
const endDate = Date.now();
console.log(requestUrl, "请求消耗时间", endDate - startDate);
resolve(res);
},
fail: e => {
console.error('网络请求失败:', e);
uni.showToast({
title: e.errMsg || '发送请求失败,请稍后再试!',
icon: 'none'
});
reject(e);
},
complete: () => {
if (showLoading) {
uni.hideLoading();
}
}
});
});
}
/**
* 发送GET请求
* @param {String} url 请求地址
* @param {Object} data 请求参数
* @param {Boolean} showLoading 是否显示加载提示
* @returns {Promise} 返回请求Promise
*/
static get(url, data = {}, showLoading = false) {
return request.request(url, data, 'GET', showLoading);
}
/**
* 发送POST请求
* @param {String} url 请求地址
* @param {Object} data 请求参数
* @param {Boolean} showLoading 是否显示加载提示
* @returns {Promise} 返回请求Promise
*/
static post(url, data = {}, showLoading = false) {
return request.request(url, data, 'POST', showLoading);
}
/**
* 发送get请求如果缓存存在则返回缓存数据否则发送请求并缓存数据
* @param {String} url 请求地址
* @param {Object} data 请求参数
* @param {Number} time 缓存时间
* @param {Boolean} showLoading 是否显示加载提示
* @returns {Promise} 返回请求Promise
*/
static async getOrCache(url, data = {}, time = 300, showLoading = false) {
const cacheKey = 'cache_' + url + '_' + qs.stringify(data);
// console.log('getOrCache', cacheKey, '查询缓存');
const cacheData = getLocalStorage(cacheKey);
if (cacheData) {
console.log('getOrCache', cacheKey, '缓存命中');
return cacheData;
}
const res = await request.request(url, data, 'GET', showLoading);
setLocalStorage(cacheKey, res, time);
return res;
}
}
export default request;

View File

@ -109,3 +109,20 @@ export function hideLoading() {
});
});
}
let os = '';
/**
*
*/
export function getOS() {
if (os != '') {
return os;
}
// #ifdef APP-PLUS
const systemInfo = uni.getSystemInfoSync();
return systemInfo.platform === 'ios' ? 'ios' : 'android';
// #endif
return 'mp';
}

7
package-lock.json generated
View File

@ -8,6 +8,7 @@
"@dcloudio/uni-ui": "^1.5.7",
"crypto-js": "^4.2.0",
"js-md5": "^0.8.3",
"lodash": "^4.17.21",
"qs": "^6.14.0"
},
"devDependencies": {
@ -685,6 +686,12 @@
"url": "https://github.com/sponsors/antfu"
}
},
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"license": "MIT"
},
"node_modules/magic-string": {
"version": "0.30.17",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz",

View File

@ -3,6 +3,7 @@
"@dcloudio/uni-ui": "^1.5.7",
"crypto-js": "^4.2.0",
"js-md5": "^0.8.3",
"lodash": "^4.17.21",
"qs": "^6.14.0"
},
"devDependencies": {

View File

@ -1,18 +1,17 @@
{
"pages": [ //pageshttps://uniapp.dcloud.io/collocation/pages
{
"path": "pages/index/index",
"style": {
"navigationStyle": "custom"
}
},
{
"path": "pages/home/home-page",
"style": {
"navigationStyle": "custom",
"navigationBarTitleText": ""
}
}, {
"path": "pages/index/index",
"style": {
"navigationStyle": "custom",
"navigationBarTitleText": ""
}
},
{
"path": "pages/bags/bags-page",
@ -78,7 +77,6 @@
"backgroundColor": "#F8F8F8"
},
"uniIdRouter": {},
"tabBar": {
"color": "#FFFDF1",
"selectedColor": "#333333",

View File

@ -1,32 +1,24 @@
<template>
<view class="content">
<image src="/static/bg.png" style="width: 100vw; height: 100vh;"></image>
</view>
</template>
<script>
export default {
data() {
return {
<script setup>
import { getConfig } from '@/common/server/config';
onLoad(async () => {
let res = await getConfig();
console.log(res);
sleep(200);
}
},
onLoad() {
},
methods: {
}
}
})
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
</style>

BIN
static/bg.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 257 KiB

View File

@ -31,18 +31,10 @@ export default defineConfig({
return `https://guyu-1308826010.cos.ap-shanghai.myqcloud.com/${path}`
}
);
// code.replace(
// /@\/?([^\s"'()]+)/g,
// (match) => {
// count++
// return 'https://guyu-1308826010.cos.ap-shanghai.myqcloud.com/' + match
// .replace(/^http:\/\/@\/?/, '')
// }
// )
if (count > 0) {
console.log(id, `本次替换了 ${count} 个图片地址`)
}
// console.log(id, fcode)
// console.log(id)
return {
code: replacedCode,
map: null