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

NodeJS实现用户取消关注接口报UnhandledPromiseRejectionWarning错误

代码存在3处核心问题,修复方案如下:

1. 用户查询逻辑完全错误

你两次调用User.findById都传入了req.params.id,导致查询到的user和currentUser是同一个用户(即你要取关的目标用户),完全没有拿到发起取关请求的当前用户数据:

// 错误写法
const user = await User.findById(req.params.id);
const currentUser = await User.findById(req.params.id); // 这里应该传入req.body.userId才是当前请求用户

同时后续更新当前用户时操作的字段也错误:你操作的是followers粉丝字段,实际应该操作当前用户的following关注字段,删除目标用户id才对。

2. 响应写法错误导致重复返回

你代码里res.send(403).json("you already unfollowed this user ")是完全错误的写法:res.send(403)已经直接把响应返回给客户端了,后续调用.json()会尝试再次设置响应头、发送响应,就触发了你看到的Cannot set headers after they are sent to the client报错。
同时这个写法也是express deprecated res.send(status)警告的来源,express早已不推荐直接给res.send()传状态码,设置状态码请统一使用.status()方法。

3. 取关功能逻辑错误

取关操作需要完成两个更新:

  • 目标用户的粉丝列表(followers)删除当前用户id
  • 当前用户的关注列表(following)删除目标用户id
    你原代码两次更新都是删除followers字段,逻辑完全不符要求。

修正后完整代码

router.put("/:id/unfollow",async (req,res) => {
    if(req.body.userId !== req.params.id){
        try{
            // 目标用户:要被取关的用户
            const targetUser = await User.findById(req.params.id);
            // 当前用户:发起取关请求的用户
            const currentUser = await User.findById(req.body.userId);
            if (targetUser.followers.includes(req.body.userId)){
                // 目标用户粉丝列表删当前用户
                await targetUser.updateOne({$pull:{followers:req.body.userId}});
                // 当前用户关注列表删目标用户
                await currentUser.updateOne({$pull:{following:req.params.id}});
                res.status(200).json("user has been unfollowed");
            }else{
                // 把send改成status即可
                res.status(403).json("you already unfollowed this user ");
            }

        }catch (err){
            res.status(500).json(err);
            console.log(err);
        }
    } else{
        res.status(403).json("You cant unfollow yourself")
    }
})

内容的提问来源于stack exchange,提问作者Code With Banchi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:09:02