Router based redirect bugs
I'm trying to have a router redirect based on it's mount point.
This router
var adminRouter = express.Router();
adminRouter.get("/", function(req,res){res.redirect("index");});
app.use("/admin", adminRouter);
correctly redirects from /admin/ to /index but redirects /admin to /index.
I tried adding
adminRouter.get("", function(req,res){res.redirect("index");});
but /admin still redirects to /index.
Weirdly, an absolute redirect
adminRouter.get("/", function(req,res){res.redirect("/admin/index");});
correctly redirects /admin to /admin/index.
Nested paths also present problem with routers being unaware of their mount point
adminRouter.get("/foo/bar", function(req,res){res.redirect("index");});
redirects /admin/foo/bar to /admin/foo/index.
And
adminRouter.get("/foo/bar", function(req,res){res.redirect("/index");});
redirects /admin/foo/bar to /index.
Interesting. I'm feeling like this is a bug, personally.
Yeah, I think the first one is pretty clearly a bug. The nested paths may be a design feature, but if so there really needs to be a way to accomplish mount-absolute redirects.
So here's the deal with res.redirect: it does nothing special with the URL it gives you; the browser is doing the relative redirect. If the request was the URL /foo/bar and you redirect to index, the browser does a standard /foo/index. If the request was for /foo/bar/ then the browser would have redirected to /foo/bar/index.
In light of this, I don't think it is any bug in express, because express actually do nothing to the location to give to redirect in the first place.
Having a mount-absolute redirect is a feature request, then.
The "" vs "/" behavior still seems like a bug. It looks like when mounting a router, the empty string route isn't appended onto the mount point.
We decided to make res.redirect stupid and leave it up to the browser. So the fix here is to ensure a trailing / for those types of paths.