Jason Brubaker Jason Brubaker - 29 days ago 15
Node.js Question

How do I do URL rewriting in Express JS 4

I'm trying to do URL rewriting in Express JS 4. Everything I read says that I should be able to overwrite the request.url property in middleware. The two existing Node modules that do rewrite use this method. However, when I try to do this:

app.use('/foo', function(req, res){
var old_url = req.url;
req.url = '/bar';

console.log('foo: ' + old_url + ' -> ' + req.url);
});

app.get('/bar', function(req, res) {
console.log('bar: ' + req.url);
});


it just doesn't work.

One note that might help: it appears that
req.url
above always is
/
regardless of the actual URL used. Did Express 4 change how the URL is maintained, and not update their documentation? How do I accomplish URL rewriting in Express 4?

Answer

If you want processing to continue after your change, you have to call next() in your middleware to keep the processing going on to other handlers.

app.use('/foo', function(req, res, next){
    var old_url = req.url;
    req.url = '/bar';

    console.log('foo: ' + old_url + ' -> ' + req.url);
    next();
});

The doc for req.originalUrl says this:

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. For example, the “mounting” feature of app.use() will rewrite req.url to strip the mount point.

Which certainly implies that you can change req.url to change the routing.


Related answer:Rewrite url path using node.js