node.jsexpressgethttp-redirect

How to redirect URL while maintaining all GET parameters using express / Node.js


Using Express/Node.js I receive GET requests with an unknown number of parameters. The names of parameters are not always known in advance. I need to redirect these requests to a new URL while maintaining all existing GET parameters.

ie. I might get any of these

http://example.com/example
http://example.com/example?id=xxx
http://example.com/example?a=xxx&_b=xxx...
etc

which in turn need to be redirected to:

http://newexample.com/example
http://otherdomain.org/sample?type=new&id=xxx
http://newexample.com/sample?a=xxx&_b=xxx...
etc

I've written this code to achieve this, but it feels like this would be common functionality that would already exist in the framework. Is there a better way?

app.get('/example', function(req, res){
    var oldParams = ""
    var redirectUrl = config.exampleUrlNew;
    if (req.originalUrl != null && req.originalUrl.indexOf('?') > 0) {
      oldParams = req.originalUrl.split("?")[1];
    }
    if (oldParams != "" && redirectUrl.indexOf('?') > 0) {
      oldParams = "&" + oldParams;
    } else {
      oldParams = "?" + oldParams;
    }
    res.redirect(redirectUrl + oldParams)
});

Solution

  • Using the url module

    var URL = require('url');
    
    var newUrl = URL.parse(oldUrl, true); // true to parse the queryString as well
    
    newUrl.host = null; // because
    newUrl.hostname = 'newexample.com';
    
    newUrl.search = null; // because
    newUrl.query.newParam = 'value';
    
    newUrl = URL.format(newUrl);
    

    There's a quirk that you have to set .host property to null for .hostname property to take precedence, because acc to the docs setting the hostname only works if the host isn't present, which it is since it's parsed from oldUrl. Ditto for .search and .query