'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.
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Apoorva Chikara |
| Solution 2 | perthos |
