In Express 5, what do app.METHOD, app.all and app.route register, and which handler answers when two registered routes match one request?
answer
- method plus path
- every verb versus one verb
- one path, chained verbs
- registration order, no ranking
basics
~20 sapp.get, app.post and the other app.METHOD calls register a handler for one HTTP method and path, app.all for every method, and app.route chains several methods on one path. Express runs the first registered route that matches.
solid answer
~40 sEach `app.METHOD` call, such as `app.get` or `app.post`, adds a route for one HTTP method and one path; `app.all` adds a route that matches the path for any method; `app.route(path)` returns a single `Route` on which you chain `.get()`, `.post()` or `.all()` so the path is written once. A route can take several callbacks or arrays of them, each passing control with `next()`. Express keeps everything in one stack in registration order and walks it top to bottom: the first route whose method and path match runs, with no ranking of literal paths above parameters, so `/products/:id` registered first also answers `/products/featured`. The query string is ignored, `app.get` also answers HEAD, and a known path requested with an unrouted method such as DELETE still gets a 404.
code
javascript · 17 linesconst express = require('express');
const app = express();
app.all('/products/:id', (req, res, next) => {
console.log(req.method, req.params.id);
next();
});
// Registered first, so it also answers GET /products/featured
app.get('/products/:id', (req, res) => res.json({ id: req.params.id }));
app.get('/products/featured', (req, res) => res.json({ featured: true }));
app.route('/products')
.get((req, res) => res.json([]))
.post((req, res) => res.status(201).json({ created: true }));
app.listen(3000);go deeper
Recall the three registration calls: app.get and friends for one verb, app.all for every verb, app.route to chain verbs on one path, and that the first registered match runs.
Explain the single ordered stack, why a parameter route registered first shadows a literal one, and the built-in HEAD, OPTIONS and 404 behaviour.
Show how you would find a shadowed route in a large app, keep literal paths ahead of parameters, and decide where a not-found handler belongs.
Weigh a convention such as one app.route block per path against free-form registration, and how the team keeps route order reviewable as files grow.
## Registering a route In Express a **route** is a pair of an HTTP method and a path, plus one or more callback functions. You add one with the methods on the application object (and the same methods exist on an `express.Router`): - **`app.METHOD(path, ...callbacks)`**: `METHOD` is a lowercase HTTP method, so the real calls are `app.get()`, `app.post()`, `app.put()`, `app.delete()`, `app.patch()` and so on. The route matches only that method. - **`app.all(path, ...callbacks)`**: matches the path for **every** HTTP method. It is the usual place for logic that must run before any verb on one path, such as loading or logging, before a later route sends the response. - **`app.route(path)`**: returns a single **`Route`** object. You chain `.all()`, `.get()`, `.post()` and the rest on it, so a path such as `/products` is typed once instead of once per verb. A path here is a **path pattern**, not a prefix. `app.all('/secret', fn)` runs for `/secret` but not for `/secret/anything`; mounting a whole sub-tree under a prefix is the job of `app.use`, which is a middleware mechanism rather than a route. ## Several callbacks on one route Every routing method accepts any mix of functions and arrays of functions. They run in order and behave like middleware: each one either sends a response or calls `next()` to pass control to the next callback. Typical uses are a small precondition check followed by the real handler, or a shared array of steps reused across routes. ```js app.get('/products/:id', checkId, loadProduct, (req, res) => { res.json(req.product); }); ``` ## How Express picks the handler Express does not build a ranked table of routes. Everything you register, routes and middleware alike, goes into **one ordered stack**, and each request walks it like this: 1. Start at the first layer registered. 2. Skip any layer whose path does not match the request path (the query string is never part of this test). 3. For a route layer, also skip it when the route has no handler for the request method. 4. Run the first layer that matches; it continues the walk only by calling `next()`. 5. If the walk reaches the end without a response, the built-in final handler answers 404. The consequence is that **the first registered match wins**. With `app.get('/products/:id', ...)` registered before `app.get('/products/featured', ...)`, a request for `/products/featured` runs the parameter route with `req.params.id` set to `'featured'`; the literal route is never reached unless the first handler calls `next()`. The fix is to register literal paths before parameter paths, or to make the parameter route decide and hand on. ## What Express answers on its own | Request | What Express does | | --- | --- | | `HEAD /books` with only `app.get('/books')` | Runs the GET handler and sends the headers without a body | | `OPTIONS /books` with no OPTIONS handler | Replies with an `Allow` header listing the methods routed on that path | | `DELETE /books` with only GET and POST routed | Falls through to the final handler: 404 `Cannot DELETE /books` | | `GET /books?page=2` | Matches `/books`; the query string plays no part in routing | Two details in that table surprise people. The HEAD behaviour applies only if `app.head()` was not registered for the path before `app.get()`. And Express does **not** answer 405 for a path that exists under another method: the request simply finds no matching route and ends at the 404. ## Using app.route well `app.route()` keeps a resource's verbs together and rules out typos between them. Its ordering follows the moment the **route** is created, not the moment each method is added: handlers chained onto that `Route` later still sit at its original position in the stack. Calling `app.route('/books')` a second time creates a second, separate route further down. ## Common mistakes - Expecting Express to prefer the most specific path; it uses registration order only. - Treating `app.all` as a prefix mount; it matches the full path, just for every method. - Writing a route per query parameter value; the query string is not matched. - Assuming a missing method yields 405; Express falls through to a 404 unless you add one. - Forgetting that a callback which neither responds nor calls `next()` stops the walk.
- In Express 5, where does a handler chained onto app.route('/books') sit in the stack if it is added after other app.get calls?At the position of the route itself. Ordering follows when `app.route('/books')` created the `Route`, and every method handler chained onto it belongs to that slot, however late it is added. Calling `app.route('/books')` again creates a second route at the current end of the stack.
- What does an Express 5 app send when no registered route matches the request?The walk reaches the end of the stack and the built-in final handler responds with a 404 and a small HTML page reading `Cannot GET /path` (with the request method in place of GET). Apps that serve JSON usually register their own not-found handler after every route so clients get a consistent body.
- Can an Express route take an array of handler functions instead of separate arguments?Yes. `app.get(path, [a, b], c)` is valid: Express flattens functions and arrays into one ordered list. Each callback must call `next()` to reach the following one, which makes arrays a convenient way to reuse a fixed sequence of checks on several routes.
A mail room that reads its sorting rules top to bottom: the first rule that fits the envelope picks the tray, even when a more precise rule sits further down the list.
- Express ranks literal paths above :param paths, so registration order does not matter.
- app.all('/secret') also runs for /secret/anything, like a prefix mount.
- app.route creates a separate mini-app that must be mounted with app.use.
- Express answers 405 automatically when the path exists under another method.
- The query string is part of the route match, so /books?page=2 needs its own route.