redben redben - 2 months ago 13
Node.js Question

In App redirect in expressjs using middleware

I am trying to make a middleware for handling url aliases, what I am doing right now is :

// [...]
module.exports = function() {

return function(req, res, next) {
// getAlias would get an object {alias:"alias/path",source:"/real/path"} or null
var alias = getAlias(req.url);
if(alias) {
req.url = alias.source;
}
next();
};

};


So basicaly I am looking in a store for the requested url and if it is found as an alias I change request.url to the source path to that alias so that express calls the right route.

The problem is request.url and request.path have the same value, but changing request.path does not work while request.url works. In addition I am not sure which one i have to test agains.

Things work when I interact with request.url but just wanted to make sure that I am doing it the proper way.

Any thoughts ?

Answer

Rewriting the req.url property is the correct way for internally rerouting requests. That is why there is a req.originalUrl for the cases where one does change the original URL.

This is what the Express documentation states for req.originalUrl:

This property is much like req.url, however it retains the original request url, allowing you to rewrite req.url freely for internal routing purposes.

The req.url property isn't documented, but from the statement above you can infer it's meant to be used in the way you explained. It is also used in that way in some of the Express tests.