node.js redirect with query string

Previously, I discussed javascript appending to query string, where we serialized an associative array to a query string. I would now like to leverage this technique within node.js as a redirect service.

Specifically, I am using express to make a web app in node.js and the app includes a redirect service, e.g.,

var app = express();
var redirectVars = {'foo':'spam and eggs', 'tracker':42 };

// redirect and append redirectVars
app.get('/redirect', function(request, result, next) {
  if(request.query.url) {
    var urle = request.query.url;
    var url = decodeURIComponent(urle);
    var firstSeperator = (url.indexOf('?')==-1 ? '?' : '&');

    var queryStringParts = new Array();
    for(var key in redirectVars) {
      queryStringParts.push(key + '=' + encodeURIComponent(redirectVars[key]));
    }
    var queryString = queryStringParts.join('&');

    result.redirect(url + firstSeperator + queryString);
  }
  result.send("400", "Bad request");
});

Usage of this service is as simple as,

/redirect?url=new-location

Any external app could use this service, which will append server controlled query string variables to the redirected URL. This is useful for a redirect service that needs to dynamically construct query string variables, such as cross-domain authentication and authorization.

Importantly, in order to preserve an existing query string in the new-location, simply encode the entire URL string before sending it into the service, e.g.,

var new_location = encodeURIComponent("http://foo.com/?q=test");
window.location = "http://www.yourapp.com/redirect?url=" + new_location;

Using the above node.js example, this would have the effect of redirecting the user to

http://foo.com/?q=test&foo=spam%20and%20eggs&tracker=42
This entry was posted in javascript. Bookmark the permalink.

Comments are closed.