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

104
Visualizações
Express js conditional statement to choose between middleware modules

I have an endpoint in express.js which is conditionally choosing between middlware callbacks to execute:

const middleware1 = require('./m1')
const middleware2 = require('./m2')
app.get('/call', async (req, res) => {
  if (req.code === 'something') {
    middleware1.call
  } else if (req.code === 'something else') {
    middleware2.call
  } else {
    res.send({
      done: "done"
    })
  }
})

middleware1

module.exports = {
  call : async function(req, res, next) {
    // does some async stuff with req
    // sends it as response
    res.send({data: "data"})
  }
}

Similar idea for middleware2. The problem is once middleware1 or middleware2` is called the request is not closing. However if, as a test, I remove the conditional statement and call one middleware immediately like so:

app.get('/call', middleware1.call); 

This works immediately, why is that? I must be doing something wrong.

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

0

Try adding next() to the end of your middleware. So that the request gets passed to the next function in the stack. More on middleware here Writing middleware for use in Express apps.

about 4 years ago · Juan Pablo Isaza Relatório

0

YOu might need to do this:

const middleware2 = require('./m2')
app.get('/call', async (req, res, next) => {
  if (req.code === 'something') { 
    middleware1.execute(req, res, next); // you were not calling the method
  } else if (req.code === 'something else') {
    middleware2.execute(req, res, next);
  } else {
    res.send({
      done: "done"
    })
  }
})
module.exports = {
// call is the reserved keyword use something different
  execute : async function(req, res, next) {
    // does some async stuff with req
    // sends it as response
    res.send({data: "data"})
  }
}

res.send should send the response back, however, in your case it seems the call to any middleware is not happening. Internally, res.send does call the next to send the response back and should send it.

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