You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

更新用户资料时无头像触发Internal Server Error问题求助

问题分析

当不上传头像更新资料时触发Internal Server Error,核心问题出在两处:

  1. 判断逻辑错误:前端未上传头像时,req.body.avatar通常为undefined,但代码中if (req.body.avatar !== "")会将undefined判定为非空值,错误进入头像处理流程
  2. 未做存在性校验:如果用户原本没有设置过头像,user.avatar为undefined,执行user.avatar.public_id时会抛出「Cannot read property 'public_id' of undefined」的错误,引发服务器内部异常
修复代码

调整判断逻辑并增加头像存在性校验:

exports.updateProfile = catchAsyncErrors(async (req, res, next) => {

    const newUserData = {
        name: req.body.name,
        email: req.body.email,
    };

    // 仅当存在有效头像链接时才处理更新
    if (req.body.avatar && req.body.avatar !== "") {
        const user = await User.findById(req.user.id);
    
        // 先确认用户已有头像,再执行销毁操作
        if (user.avatar?.public_id) {
            await cloudinary.v2.uploader.destroy(user.avatar.public_id);
        }
    
        const myCloud = await cloudinary.v2.uploader.upload(req.body.avatar, {
          folder: "avatars",
          width: 150,
          crop: "scale",
        });
    
        newUserData.avatar = {
          public_id: myCloud.public_id,
          url: myCloud.secure_url,
        };
      }
    const user = await User.findByIdAndUpdate(req.user.id, newUserData, {
        new: true,
        runValidators: true,
        useFindAndModify: false
    })

    res.status(200).json({
        success: true
    })
});
额外建议
  • 可在catchAsyncErrors中打印具体错误栈,方便快速定位问题
  • 前端未上传头像时,建议明确传递空字符串而非省略该字段,避免判断歧义

内容的提问来源于stack exchange,提问作者DevBobi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 12:45:45