Skip to content

Instantly share code, notes, and snippets.

@ramonfritsch
Created November 9, 2016 17:06
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramonfritsch/06893c1c561d670687a9aee3bbc4e9c7 to your computer and use it in GitHub Desktop.
Save ramonfritsch/06893c1c561d670687a9aee3bbc4e9c7 to your computer and use it in GitHub Desktop.
URL rewrite on ExpressJS 4.0
....
//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');
});
....
@pruthvivrp
Copy link

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 ?

@mosfet1kg
Copy link

Thanks a lot!! it works for me

@puranik3
Copy link

Shouldn't line 17 be this? (you have reset res.url not req.url)

req.url = '/other/route2/';

@ramonfritsch
Copy link
Author

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