Home > other >  Express js conditional statement to choose between middleware modules
Express js conditional statement to choose between middleware modules

Time:03-29

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related