Calling Express Route internally from inside NodeJS

Solution 1:

The 'usual' or 'correct' way to handle this would be to have the function you want to call broken out by itself, detached from any route definitions. Perhaps in its own module, but not necessarily. Then just call it wherever you need it. Like so:

function updateSomething(thing) {
    return myDb.save(thing);
}

// elsewhere:
router.put('/api/update/something/:withParam', function(req, res) {
    updateSomething(req.params.withParam)
    .then(function() { res.send(200, 'ok'); });
});

// another place:
function someOtherFunction() {
    // other code...
    updateSomething(...);
    // ..
}

Solution 2:

This is an easy way to do an internal redirect in Express 4:

The function that magic can do is: app._router.handle()

Testing: We make a request to home "/" and redirect it to otherPath "/other/path"

var app = express()

function otherPath(req, res, next) {
  return res.send('ok')
}

function home(req, res, next) {
  req.url = '/other/path'
  /* Uncomment the next line if you want to change the method */
  // req.method = 'POST'
  return app._router.handle(req, res, next)
}

app.get('/other/path', otherPath)
app.get('/', home)

Solution 3:

I've made a dedicated middleware for this : uest.

Available within req it allows you to req.uest another route (from a given route).

It forwards original cookies to subsequent requests, and keeps req.session in sync across requests, for ex:

app.post('/login', async (req, res, next) => {
  const {username, password} = req.body

  const {body: session} = await req.uest({
    method: 'POST',
    url: '/api/sessions',
    body: {username, password}
  }).catch(next)

  console.log(`Welcome back ${session.user.firstname}!`

  res.redirect('/profile')
})

It supports Promise, await and error-first callback.

See the README for more details