express icon indicating copy to clipboard operation
express copied to clipboard

Router based redirect bugs

Open seth-admittedly opened this issue 12 years ago • 6 comments

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.

seth-admittedly avatar Apr 29 '14 17:04 seth-admittedly

Interesting. I'm feeling like this is a bug, personally.

dougwilson avatar Apr 29 '14 18:04 dougwilson

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.

seth-admittedly avatar Apr 29 '14 18:04 seth-admittedly

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.

dougwilson avatar Apr 29 '14 18:04 dougwilson

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.

dougwilson avatar Apr 29 '14 18:04 dougwilson

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.

seth-admittedly avatar Apr 29 '14 18:04 seth-admittedly

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.

defunctzombie avatar Apr 29 '14 18:04 defunctzombie