Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
Cannot set headers after they are sent to the client - Express JS

I am pretty much new to node / express and following a youtube tutorial to build a MERN Stack app. But my node server is giving this error

error

I tried restarting server many times it happening again and again. I got the idea it happens when we send two responses for one request but I don't think its the case here.

Btw here is the route it is pointing to in the error (in the try catch error response line)

// GET RANDOM
router.get("/random", verify, async (req, res) => {
    const type = req.query.type;
    let movie;
    try {
      if (type === "series") {
        movie = await Movie.aggregate([
          { $match: { isSeries: true } },
          { $sample: { size: 1 } },
        ]);
      } else {
        movie = await Movie.aggregate([
          { $match: { isSeries: false } },
          { $sample: { size: 1 } },
        ]);
      }
      res.status(200).json(movie); //checked here by console logging it comes here only once
    } catch (err) {
      res.status(500).json(err); //the error pointing to this line
    }
});

Just in case, here is the verify function code:

function verify(req,res,next) {
    const authHeader = req.headers.token;
    if(authHeader){
        const token = authHeader.split(' ')[1];

        jwt.verify(token,process.env.SECRET_KEY,(err,user) => {
            if(err) res.status(403).json("Token is not valid");
            req.user = user;
            next();
        })
    } else{
        return res.status(401).json("Unauthorized");
    }
}
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda