Home > OS >  Express route return instead of res.send()?
Express route return instead of res.send()?

Time:01-31

Is it possible to return the value required for res.send() inside a route?

As opposed to specifically call res.send(value) in the route?

I tried this, and created a middleware at the end of the chain that will call res.send(), but apparently it never reaches it. Also, even if it did, how can I get the return value from the prev route to put it inside send() ?

CodePudding user response:

Not tested, but this should work

Function:

function handler(callback) {
  return (req, res) => {
    res.json(callback(req, res))
  })
}

Usage:

app.get('/', handler((req, res) => {
  return { test: 1 }
})
  • Related