'Express: why middlewares doesn't work properly for independent routers?
I have the following code with 3 independent routers
const Express = require("express")
const app = Express()
const usersRouter = Express.Router()
const productsRouter = Express.Router()
const storeRouter = Express.Router()
productsRouter.use((_, res, next) => {
res.send("products fail")
//next()
})
storeRouter.use((_, res, next) => {
res.send("store fail")
//next()
})
usersRouter.route("/users")
.get((_, res) => res.send("users"))
productsRouter.route("/products")
.get((_, res) => res.send("products"))
storeRouter.route("/store")
.get((_, res) => res.send("store"))
app.use(usersRouter)
app.use(productsRouter)
app.use(storeRouter)
app.listen(80, () => console.log("running"))
But every time I request /store route it pass through productRouter middleware which is assigned only to it.
I can't understand this behavior.
Why is this? How can I manage independent middlewares for each one?
GET /store 200
products fail
Expected
GET /store 200
store fail
Solution 1:[1]
When you do this:
app.use(productsRouter)
that sends ALL requests to the productsRouter and thus its middleware runs for all requests. So, when you have this:
productsRouter.use((_, res, next) => {
res.send("products fail")
//next()
});
That will run on every single request.
If you want the router to only see certain requests, then register the router on a path instead so the router only gets requests destined for a certain path.
app.use("/products", productsRouter)
And, then remove the path itself from the router's routes since the path will have already been filtered.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jfriend00 |
