Reputation: 93
i'm currently working on a project with node.js. I stucked at a specific problem. After adding all routes with express (app.get("..", func)) I end up with a middleware that catches all requests and redirects to a 404-page.
The thing is now, when I add a route afterwards during server run, the middleware doesent care about the new route.
example:
app.get("/home", function(_, res) {
res.send("home");
})
app.get("/faq", function(_, res) {
res.send("faq");
})
app.use(function(_, res) {
res.send("404");
});
// e.g. 10 min later..
app.get("/team", function(_, res) {
res.send("team");
})
So i can access /home and /faq but after 10 min requesting the page /team, i am redirected to the 404 page.
Does anybody know a solution ? Im quite new to nodejs..
Upvotes: 0
Views: 257
Reputation: 203304
Although adding routes dynamically doesn't sound like a good idea, here's a workaround: add an (empty) Router
instance right before the 404 handler, and add the new routes to that router instead of to app
:
let router = express.Router();
app.use(router);
app.use(function(_, res) {
res.send("404");
});
// e.g. 10 min later..
router.get("/team", function(_, res) {
res.send("team");
})
Upvotes: 0