在 Express 中出现 "Cannot set headers after they are sent to the client" 错误

Getting "Cannot set headers after they are sent to the client" error in Express

错误截图:

客户端代码:

附上jwt api:

这是jwt验证函数:

    const authHeader = req.headers?.authorization;
    if(!authHeader){
        return res.status(401).send({message: 'Unauthorized access'})
    }
    const token = authHeader.split(' ')[1];
    jwt.verify(token, process.env.SECRET_TOKEN, (err, decoded)=>{
        if(err){
            return res.status(403).send({message: 'Forbidden access'})
        }
        console.log('decoded', decoded);
        req.decoded = decoded;
    })
    next();
}

此错误与 jwt 无关。如果您在发送响应后尝试对 res 对象执行某些操作,则会发生此错误。您可以尝试在服务器上的所有 res.send() 语句之后或与它们一起使用 return 语句,这应该可以解决此错误。