学习:uniapp全栈微信小程序vue3后台-额外/精彩报错篇
1.分类列表分页
uni-pagination | uni-app官网
Pagination Props
属性名 | 类型 | 默认值 | 说明 |
---|---|---|---|
prevText | String | 上一页 | 左侧按钮文字 |
nextText | String | 下一页 | 右侧按钮文字 |
value/v-model | Number | 1 | 当前页 |
current | Number | 1 | 当前页, 优先级高于 value |
total | Number | 0 | 数据总量 |
pageSize | Number | 10 | 每页数据量 |
showIcon | Boolean | false | 是否以 icon 形式展示按钮 |
/uniCloud-alipay/cloudfunctions/admin-wallpaper-classify/index.obj.js
/*** 获取分类列表*/async list({ current = 1, size = 10 } = {}) {try {// 从第skip条数据开始let skip = (current - 1) * size;// 初始化数据库JQL实例const dbJQL = uniCloud.databaseForJQL({clientInfo: this.getClientInfo()});const res = await dbJQL.collection("wallpaper-classify").skip(skip).limit(size).field(`name,picurl,enable,select,sort,user_id,createTime`).orderBy("sort asc").get({ getCount: true }); // 返回数据和总数return res;} catch (err) {return {errCode: 500,errMsg: "数据库查询失败",data: [],count: 0};}},
/pages/wallpaper/classify
<script setup>// 分页参数const params = ref({currentPage: 1, // 当前页码pageSize: 10, // 每页条数total: 0 // 总条数});// 获取分类列表const getClassify = async () => {try {// 解构 后端需要 current ,sizelet { errCode, errMsg, data, count } = await classifyCloudObj.list({current: params.value.currentPage,size: params.value.pageSize});if (errCode !== 0) return showToast({ title: errMsg });// 赋值classData.value = data// 总计,更新总条数params.value.total = count;console.log(data);} catch (err) {console.error("加载分类失败:", err);showToast({ title: "加载数据失败,请重试" });}}// 分页切换事件const handlePageChange = (e) => {console.log("打印当前页码:", e.current); // 打印当前页码params.value.currentPage = e.current; // 更新当前页码getClassify(); // 重新加载数据};</script>
<!-- 分页 --><view class="paging"><uni-pagination :title="`共 ${params.total} 条`" :show-icon="true" :total="params.total":current="params.currentPage" :page-size="params.pageSize" @change="handlePageChange"></uni-pagination></view>
2.管理员显示注册时间
错
1.创建超级管理员出现的问题
ai分析:
连接本地云函数
连接云端云函数
跟着第一节课步骤走,还是会出现,看来不是我的问题
好像还是我的问题,明天老师远程。
远程控制更改了我系统的时间,就好了,不到20分钟,
AI分析的
1. 可能的原因
(1) Token 或 Session 过期
- 现象:
uni-id
或uni-captcha
返回500
错误,可能与登录状态的校验有关。 - 原因:
- 系统时间不正确时,生成的 Token 或 Session 的时间戳可能被服务器判定为无效(例如,时间偏差过大)。
- 例如:
- 如果系统时间比实际时间快,Token 可能被判定为“未来生成”而失效。
- 如果系统时间比实际时间慢,Token 可能被判定为“已过期”。
(2) 证书或 HTTPS 校验失败
- 现象:本地开发服务(如
http://127.0.0.1:7001
)可能启用了 HTTPS 或证书校验。 - 原因:
- 证书的有效期依赖于系统时间。如果系统时间不在证书的有效期内,请求会被拒绝。
(3) 数据库或缓存时间同步问题
- 现象:云函数依赖的数据库(如 MongoDB)或缓存(如 Redis)可能对操作时间有严格校验。
- 原因:
- 数据库可能拒绝时间不一致的请求(例如,写入数据的
createdAt
字段时间与实际时间偏差过大)。
- 数据库可能拒绝时间不一致的请求(例如,写入数据的
(4) 定时任务或 Cron 作业
- 现象:云函数中可能有定时任务逻辑,依赖系统时间触发。
- 原因:
- 如果系统时间错误,定时任务可能无法按预期执行。
2. 解决方案
(1) 同步系统时间
- 确保系统时间与网络时间同步:
- Windows:
- 右键任务栏的时间 > “调整日期和时间”。
- 开启“自动设置时间”和“自动设置时区”。
- Windows:
2.后台下载记录报错
删掉测试图片后
未正确传入 type
参数,导致触发了这段错误
- 如果关联查询的结果为空(如
classname
、nickname
或picurl
为null
或空数组),直接访问[0]
会抛出Cannot read properties of null
错误。
解决方案:
- 增加空值判断
// 增加空值判断的处理关联字段数组let data = res.data.map(item => ({...item,classname: item.classname && item.classname.length > 0 ? item.classname[0] : '',nickname: item.nickname && item.nickname.length > 0 ? item.nickname[0] : '',picurl: item.picurl && item.picurl.length > 0 ? item.picurl[0] : ''}))
同样的问题出现在客户端,
增加空值判断的处理关联字段数组
// 增加空值判断的处理关联字段数组let data = res.data.map(item => ({...item,classname: item.classname?.[0] || '',classid: item.classid?.[0] || '',_id: item._id?.[0] || '',description: item.description?.[0] || '',picurl: item.picurl?.[0] || '',score: item.score?.[0] || 0,tabs: item.tabs?.[0] || [],user_id: item.user_id?.[0] || '',view_count: item.view_count?.[0] || 0}));
通过增加对 nickname
字段的空值判断
// 合并用户昵称(增加空值判断)data = data.map(item => ({...item,nickname: authData.find(find => find._id == item.user_id)?.nickname || '匿名用户'}));
3.排行榜错误
countTotal一直为1
/uniCloud-alipay/cloudfunctions/admin-data-overview/index.obj.js
rankOrder
async rankOrder({ type = null, dataRange = [], number = 9 } = {}) {// 确保number不超过15number = Math.min(number, 15);// 根据type确定要查询的数据表// 如果type是'download',则查询'wallpaper-download'表// 如果type是'score',则查询'wallpaper-score'表// 否则,table为空字符串let table = type == 'download' ? 'wallpaper-download' : type == 'score' ? 'wallpaper-score' : '';// 如果table为空,则输出错误信息并返回空数组if (!table) {console.error('无效的类型参数:', type);return [];}// 构建时间范围查询条件let wre = dataRange.length ?`createTime >= ${dayjs(dataRange[0]).startOf("day").valueOf()} && createTime<=${dayjs(dataRange[1]).endOf("day").valueOf()}` : {};const dbJQL = uniCloud.databaseForJQL({clientInfo: this.getClientInfo()});try {// 优先使用分组统计let { data: groupData = [] } = await dbJQL.collection(table).where(wre).groupBy("picid").groupField("count(*) as countTotal").orderBy("countTotal desc").limit(number).get();if (groupData.length === 0) {// 如果分组统计无结果,使用手动统计let { data: allRecords = [] } = await dbJQL.collection(table).where(wre).field("picid").get();// 手动统计每个picid的出现次数let countMap = {};allRecords.forEach(record => {if (record.picid) {countMap[record.picid] = (countMap[record.picid] || 0) + 1;}});// 转换为数组并排序groupData = Object.keys(countMap).map(picid => ({picid,countTotal: countMap[picid]})).sort((a, b) => b.countTotal - a.countTotal).slice(0, number);}if (groupData.length === 0) return [];// 获取壁纸详情// 使用groupData数组生成picid数组,并过滤掉空值let picidArr = groupData.map(item => item.picid) // 使用map方法提取每个元素的picid属性.filter(Boolean); // 使用filter方法过滤掉所有假值(null、undefined、0、false、NaN、空字符串)let { data: piclist = [] } = await dbJQL.collection("wallpaper-piclist").where(`_id in ${JSON.stringify(picidArr)}`).field("_id,picurl").get();// 合并数据return groupData.map(item => {let pic = piclist.find(p => p._id === item.picid);return {picid: item.picid,countTotal: Number(item.countTotal) || 0,picurl: pic?.picurl || ''};});} catch (error) {console.error('Failed to get rank data:', error);return [];}},
没修好,除了第一张图countTotal显示其他,
4.排序错误
评分取整
<!-- 评分 --><uni-td class="score"><uni-rate class="uni-rate" :disabled="true" disabledColor="#F7E7CE" size="16":value="item.score" /><text class="text">{{Number(item.score).toFixed(1)}}</text></uni-td>