Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
I get the " Cannot set headers after they are sent to the client " error with node-js

I'm coding the backend of a wbesite for a school project, and i got an error in the likes and dislikes part of my code. I get the " Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" when i try to remove like but when i use promises instead of async in my removeLike function it's working.

    async function likeSauce(req, res) {
    if (![1, -1, 0].includes(req.body.like)) {
        return res.status(403).send({ message: "Invalid like value" })
    } else {
        await addLike(req, res)
        await addDislike(req, res)
        await removeLike(req, res)
        await removeDislike(req, res)
    }
}


async function addLike(req, res) {
    if (req.body.like === 1) {
        try {
            await Product.findOneAndUpdate({ _id: req.params.id }, { $inc: { likes: 1 }, $push: { usersLiked: req.body.userId } })
            return res.status(200).send({ message: "Like added !" })
        } catch (error) {
            res.status(400).send({ error })
        }
    }
}

async function addDislike(req, res) {
    if (req.body.like === -1) {
        try {
            await Product.findOneAndUpdate({ _id: req.params.id }, { $inc: { dislikes: 1 }, $push: { usersDisliked: req.body.userId } })
            return res.status(200).send({ message: "Dislike added !" })
        } catch (error) {
            res.status(400).send({ error })
        }
    }
}


async function removeLike(req, res) {
    const resultat = await Product.findOne({ _id: req.params.id })
    if (resultat.usersLiked.includes(req.body.userId)) {
        try {
            await Product.findOneAndUpdate({ _id: req.params.id }, { $inc: { likes: -1 }, $pull: { usersLiked: req.body.userId } })
            return res.status(200).send({ message: "Like removed !" })
        } catch (error) {
            res.status(400).send({ error })
        }
    }
}

async function removeDislike(req, res) {
    const resultat = await Product.findOne({ _id: req.params.id })
    if (resultat.usersDisliked.includes(req.body.userId)) {
        try {
            await Product.findOneAndUpdate({ _id: req.params.id }, { $inc: { dislikes: -1 }, $pull: { usersDisliked: req.body.userId } })
            return res.status(200).send({ message: "Dislike removed !" })
        } catch (error) {
            res.status(400).send({ error })
        }
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

That's because you use await for:

await addLike(req, res)
await addDislike(req, res)
await removeLike(req, res)
await removeDislike(req, res)

This will instruct node.js to wait for functions completions, but in all of theses functions, you return with a res.send.

So after, the first call Express has already send the response, and second function call will générate your error while trying to res.send

You must take advantage of Node.js aysnchronous bay using callbak or better promise.

You should res.send only once.

promisify your 4 functions and use then() and catch() to call them. And then call res.send only once in the last then().

Also, you should test like value before calling functions, doing this you will not call all function, but just the right one.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Always do return res, even in catch section

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda