Reputation: 685
I am working on an express app and am new to the framework. I have a few routes I'd like to redirect to one without doing something like:
var router = require("express").Router();
router.all("/route", function(req, res){
res.redirect("/repetitive");
});
router.all("/route2", function(req, res){
res.redirect("/repetitive");
});
This is a contrived example, but I'm looking for a way to have many routes redirect to /repetitive
without writing lots of router.all
s , but I don't see a way in the docs. Is passing a regex to router.all
an option and if so is that the best practice for express? Thanks!
Upvotes: 1
Views: 2025
Reputation: 20015
What about the following?
var r = function(req, res) {
res.redirect("/repetitive");
}
var routes = ["/route", "/route2"];
for (var i in routes)
router.all(routes[i], r);
or if names follow a regular expression pattern:
router.all(/\/route\d*/, function(req, res) {
res.redirect("/repetitive");
});
The above will match "/route" optionally followed by a number.
Upvotes: 1