expressjs.com icon indicating copy to clipboard operation
expressjs.com copied to clipboard

Add API docs for router(req, res, [next])

Open dougwilson opened this issue 4 years ago • 4 comments

The instance function router(req, res, [next]) I can't find documented in the API docs. We should get it listed there and documented, somewhere in the http://expressjs.com/en/4x/api.html#router section.

The same docs would be in the 4x and 5x API docs.

dougwilson avatar May 15 '20 18:05 dougwilson

I didn't fully understand this, so I created an example snippet:

const express = require('express');

const app = express();
const router = express.Router();

router.get('/foo', (req, res, next) => {
  console.log('ROUTER HIT');
  res.json({ ok: true });
});

app.get('*', (req, res, next) => {
  req.url = '/foo';
  router(req, res, next);
});

const PORT = process.env.PORT || 8000;
app.listen(PORT, () => console.log(`Server listening at port ${PORT}`));

jonchurch avatar May 15 '20 18:05 jonchurch

Apologies, I just created it quickly not to forget :) Yep, that pretty much sums it up. Essentially, a router instance is a function which takes the standard three arguments res, res, next and will take the given request and route it inside itself. You can think of it like the reason you can write app.use(router) is because app.use takes a function and calls it with those three args... and router is itself a function just like that :) !

I write next in square brackets, but come to think of it, next may be required for a router (I know it is optional for an app, though).

dougwilson avatar May 15 '20 18:05 dougwilson

Is this being worked on? If not I'm happy to help.

SimplyComplexable avatar May 15 '20 20:05 SimplyComplexable

@SimplyComplexable Nope, go for it

jonchurch avatar May 15 '20 23:05 jonchurch