Nodejs : Redirect URL
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.setHe开发者_Python百科ader("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?
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:
https://github.com/visionmedia/express/blob/master/lib/response.js#L335
// 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);
};
server = http.createServer(
function(req, res)
{
url ="http://www.google.com";
body = "Goodbye cruel localhost";
res.writeHead(301, {
'Location': url,
'Content-Length': body.length,
'Content-Type': 'text/plain' });
res.end(body);
});
Yes it should be full url in setHeader
.
res.statusCode = 302;
res.setHeader('Location', 'http://' + req.headers['host'] + ('/' !== req.url)? ( '/' + req.url) : '');
res.end();
What happens if you change it to 307 instead?
This issue may also depend on the type of request you are handling. A POST request cannot be redirected using the header. For example, a first-time visitor from to your app in FB will most-likely be coming via a "signed request" POST and therefore a redirect will not work.
精彩评论