Nodejs : Redirect URL

Problem

I’m trying to redirect the url of my app in node.js in this way:

// response comes from the http server
response.statusCode = 302;
response.setHeader("Location", "/page");
response.end();

But the current page is mixed with the new one, it looks strange :| My solution looked totally logical, I don’t really know why this happens, but if I reload the page after the redirection it works.

Anyway what’s the proper way to do HTTP redirects in node?

Problem courtesy of: Adam

Solution

Looks like express does it pretty much the way you have. From what I can see the differences are that they push some body content and use an absolute url.

See the express response.redirect method:

// Support text/{plain,html} by default
if (req.accepts('html')) {
body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';
this.header('Content-Type', 'text/html');
} else {
body = http.STATUS_CODES[status] + '. Redirecting to ' + url;
this.header('Content-Type', 'text/plain');
}

// Respond
this.statusCode = status;
this.header('Location', url);
this.end(body);
};

Solution courtesy of: Geoff Chappell

View additional discussion.