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

117
Visualizações
Infinite loading on middleware when applying it to a post route

Ok so I've made a middleware that checks if the user has already submitted their data to a form, and if true; redirects them to an error page and a link to access their previous results if they wish to do that. Here is the middleware I've written:

     module.exports.isRevisit = async (req, res, next) => {
          const visitors = await Visitor.find({});
          for (const visitor in visitors) {
            if (visitor.session === visitors.session) {
              const redirectedVisitor = visitors[visitor];
              return res.render("error", { redirectedVisitor });
            } else {
              next();
            }
          }
        };

and here is the route on which I've put my middleware:

app.post("/home", isRevisit, async (req, res, next) => {
  const date = new Date();
  const today = date.getDate();
  const visitor = new Visitor({
    input: req.body.input,
    Date: today,
    session: req.sessionID,
  });

  await visitor.save();
  const goodVisitorsCount = await Visitor.count({ input: "good", Date: today });
  const badVisitorsCount = await Visitor.count({ input: "bad", Date: today });
  const allVisitorsCount = await Visitor.count({});
  //console.log(visitor.session);
  res.render(`GoodOrBad/${req.body.input}`, {
    goodVisitorsCount,
    badVisitorsCount,
    allVisitorsCount,
  });

 
});

Now when I hit the post route as a user who has yet to input their data for the first time. The page loads infinitely, but the middleware works and prevents any user from tampering with the form again. Any way to fix this? I'm super lost on this one. This is my first project using express, mongoose, and node.js!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If visitors is empty, the body of the for loop is never executed, so your middleware calls neither res.render nor next. But one of them must be called.

Also, if the body of the for loop is executed more than once, next might be called during the first exeuction and res.render during a subsequent execution. Or next might be called more than once. All this does not make sense.

You must make sure that either next is called once or res.render is called once, no matter how often the loop is executed.

I cannot be more specific, because it is unclear to me how you know who the current visitor is. That information must come from the req request object somehow.

about 4 years ago · Juan Pablo Isaza Relatório
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