Route Matching Confusion Between blogs/:id and blogs/create #6252
Answered
by
krzysdz
mitulgupta72
asked this question in
Q&A
-
Beta Was this translation helpful? Give feedback.
Answered by
krzysdz
Dec 28, 2024
Replies: 1 comment
-
If handler for const express = require("express");
const app = express();
// This route is declared first, so it has priority over parametrized one
app.get('/blogs/create', (req, res) => {
res.send('Create a blog');
});
app.get('/blogs/:id', (req, res, next) => {
// Skip this handler if the url contains non-empty "skip" parameter in query
if (req.query.skip) {
next();
return;
}
const id = req.params.id;
res.send(`Blog with id ${id}`);
});
// This handler will not be called, unless the handler for `/blogs/:id` calls `next()`
app.get('/blogs/unique', (req, res) => {
res.send('Unique blog');
});
const server = app.listen(0, "127.0.0.1", async () => {
const {address, port} = server.address();
for (const path of ["/blogs/create", "/blogs/abc", "/blogs/unique", "/blogs/unique?skip=1"]) {
const r = await fetch(`http://${address}:${port}${path}`);
const t = await r.text();
console.log(`Response from ${path}: ${t}`);
}
server.close();
}); $ node index.js
Response from /blogs/create: Create a blog
Response from /blogs/abc: Blog with id abc
Response from /blogs/unique: Blog with id unique
Response from /blogs/unique?skip=1: Unique blog |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
IamLizu
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If handler for
/blogs/create
is declared before the parametrized/blogs/:id
it will be called first. That's how route matching works in Express - the first matching handler is used. If you can't move more specific routes above the parametrized ones, you can try detecting those routes and skipping to the next matching handler usingnext()
.