Created
November 9, 2016 17:06
-
-
Save ramonfritsch/06893c1c561d670687a9aee3bbc4e9c7 to your computer and use it in GitHub Desktop.
URL rewrite on ExpressJS 4.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.... | |
//This is how you'd do on ExpressJS 3.0 | |
app.get('/my/route1/', function (req, res, next) { | |
req.url = '/other/route2/'; | |
next('route'); | |
}); | |
app.get('/other/route2/', function (req, res, next) { | |
res.send('I am other route 2'); | |
}); | |
//With the introduction of Routers on ExpressJS 4.0, we need to start from the beginning of the middleware stack again | |
var routerMy = new express.Router(); | |
app.use('/my/', routerMy); | |
routerMy.get('/route1/', function (req, res, next) { | |
res.url = '/other/route2/'; | |
app.handle(req, res, next); // <--- here | |
}); | |
var routerOther = new express.Router(); | |
app.use('/other/', routerOther); | |
routerOther.get('/other/route2/', function (req, res, next) { | |
res.send('I am other route 2'); | |
}); | |
.... |
Thanks a lot!! it works for me
Shouldn't line 17 be this? (you have reset res.url not req.url)
req.url = '/other/route2/';
Shouldn't line 17 be this? (you have reset res.url not req.url)
req.url = '/other/route2/';
Good point, now I gotta test it out to confirm.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
But with this approach in ExpressJS4.0+, the request passes through all the previous middlewares too. But for my requirement, I just need to pass it to the next matching middleware/handler. How to do that ?