Browse Source

实现商品评价删除功能:修复前端逻辑,优化错误处理,添加后端接口

pull/19/head
徐飞洋 2 months ago
parent
commit
8fcb4ababa
  1. 17
      pages/goods-detail/goods-detail.js
  2. 54
      server-example/server-mysql.js
  3. 22
      utils/api.js

17
pages/goods-detail/goods-detail.js

@ -695,27 +695,22 @@ Page({
});
} else {
// 删除失败
wx.hideLoading();
// 如果服务器删除失败,尝试本地删除
const comments = this.data.comments.filter(item => item.id !== comment.id);
wx.showToast({
title: '删除失败,请稍后重试',
icon: 'none'
});
this.setData({
comments: comments,
showDeleteConfirmModal: false,
commentToDelete: null
});
wx.showToast({
title: '删除成功',
icon: 'success'
});
}
})
.catch(err => {
wx.hideLoading();
console.error('删除评论失败:', err);
// 如果服务器删除失败(例如接口不存在404),尝试本地删除
// 如果是网络错误或服务器错误,仍然尝试本地删除
// 这样可以保证用户体验的一致性
const comments = this.data.comments.filter(item => item.id !== comment.id);
this.setData({
comments: comments,

54
server-example/server-mysql.js

@ -4427,6 +4427,60 @@ app.post('/api/comments/updateHate', async (req, res) => {
}
});
// 删除评论
app.post('/api/comments/delete', async (req, res) => {
try {
const { commentId, currentUserPhone, commentPhone } = req.body;
// 参数验证
if (!commentId) {
return res.status(400).json({
success: false,
code: 400,
message: '缺少评论ID参数'
});
}
// 验证当前用户是否有权限删除该评论
// 只有评论的所有者才能删除评论
if (currentUserPhone !== commentPhone) {
return res.status(403).json({
success: false,
code: 403,
message: '无权删除该评论'
});
}
// 从数据库中删除评论
const result = await Comment.destroy({
where: { id: commentId }
});
// 检查是否删除成功
if (result === 0) {
return res.status(404).json({
success: false,
code: 404,
message: '评论不存在或已被删除'
});
}
res.json({
success: true,
code: 200,
message: '删除评论成功'
});
} catch (error) {
console.error('删除评论失败:', error);
res.status(500).json({
success: false,
code: 500,
message: '删除评论失败',
error: error.message
});
}
});
// 修改商品
app.post('/api/products/edit', async (req, res) => {
try {

22
utils/api.js

@ -1046,6 +1046,12 @@ module.exports = {
console.log('API.deleteComment - 请求URL:', '/api/comments/delete');
console.log('API.deleteComment - 请求方法:', 'POST');
// 参数验证
if (!commentId) {
console.error('API.deleteComment - 评论ID不能为空');
return Promise.reject(new Error('评论ID不能为空'));
}
// 尝试调用服务器接口删除评论
return request('/api/comments/delete', 'POST', {
commentId: commentId,
@ -1057,10 +1063,18 @@ module.exports = {
return res;
})
.catch(err => {
console.warn('API.deleteComment - 服务器删除评论失败(可能是接口未实现):', err);
// 如果服务器返回404错误(接口不存在),直接返回成功,让客户端在本地删除评论
// 这样用户就不会看到错误提示
return { success: true, message: '评论已删除' };
console.warn('API.deleteComment - 服务器删除评论失败:', err);
// 只有当接口不存在(404)时,才返回成功让客户端在本地删除
// 这样可以避免用户看到不必要的错误提示
if (err && (err.statusCode === 404 || err.errMsg && err.errMsg.includes('404'))) {
console.warn('API.deleteComment - 接口不存在,返回本地删除成功');
return { success: true, message: '评论已删除' };
}
// 其他错误类型直接抛出,让上层处理
console.error('API.deleteComment - 删除评论失败:', err.message);
throw err;
});
},

Loading…
Cancel
Save