I\'m using Node.js with express and already know the existence of response.redirect()
.
However, I\'m looking for more of a forward()
funct
You can implement forward (aka rewrite) functionality by changing request url
property and calling next('route')
.
Note that the handler performing forward needs to be configured before other routes which you perform forwards to.
This is example of forwarding all *.html
documents to routes without .html
extension (suffix).
function forwards(req, res, next) {
if (/(?:.+?)\.html$/.test(req.url)) {
req.url = req.url.replace(/\.html$/, '');
}
next('route');
}
You call next('route')
as the last operation. The next('route')
passes control to subsequent routes.
As mentioned above, you need to configure forwards handler as one of the first handlers.
app.get('*', forwards);
// ...
app.get('/someroute', handler);
The above example will return the same content for /someroute
as well as /someroute.html
. You could also provide an object with a set of forward rules ({ '/path1': '/newpath1', '/path2': '/newpath2' }
) and use them in forward mechanism.
Note that regular expression used in forwards
function is simplified for mechanism presentation purposes. You would need to extend it (or perform check on req.path
) if you would like to use querystring parameters etc.
I hope that will help.