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

103
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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