Nodejs:redirecturl

我试图以这种方式在node.js中redirect我的应用程序的url:

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

但是当前页面和新页面混在一起,看起来很奇怪:| 我的解决scheme看起来完全合乎逻辑,我不知道为什么发生这种情况,但如果我重新加载页面redirect后,它的工作原理。

无论如何,在节点中执行HTTPredirect的正确方法是什么?

看起来快递几乎和你一样。 从我可以看到的不同之处是,他们推动一些正文内容,并使用绝对的url。

请参阅express response.redirect方法:

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); }; 

是的,它应该是setHeader完整url。

  res.statusCode = 302; res.setHeader('Location', 'http://' + req.headers['host'] + ('/' !== req.url)? ( '/' + req.url) : ''); res.end(); 

如果将其更改为307,会发生什么情况?

 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); }); 

这个问题也可能取决于您正在处理的请求的types。 POST请求不能使用标题redirect。 例如,在FB中首次访问您的应用的访问者最有可能通过“签名请求”POST进入,因此redirect将不起作用。