English 中文(简体)
Nodejs:重定向URL
原标题:Nodejs : Redirect URL

我正试图以这种方式重定向node.js中应用程序的url:

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

但当前页面与新页面混合在一起,看起来很奇怪:|我的解决方案看起来完全符合逻辑,我真的不知道为什么会发生这种情况,但如果我在重定向后重新加载页面,它会起作用。

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

最佳回答

看起来express的工作方式和你差不多。从我所看到的不同之处在于,他们推送了一些正文内容,并使用了一个绝对的url。

见明确答复。直接方法:

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

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

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

如果改为307会发生什么?

此问题还可能取决于您正在处理的请求类型。POST请求无法使用标头重定向。例如,FB中首次访问您的应用程序的用户很可能是通过“签名请求”POST来的,因此重定向将不起作用。





相关问题
How to use redirect_to to a non-Rails URL with query params?

We just had an existing use of redirect_to break due to a Rails upgrade, and it led to a question. I ve been experimenting, and I don t seem to find a way to use redirect_to to send the user to a non-...

Apache authentication: Redirect on failure, reliably?

I ve set my ErrorDocument 401 to point to my website s account creation page, but not all browsers seem to honor this redirect (Safari). Also, other browsers (Firefox, Chrome) never quit asking for ...

Response.Redirect HTTP status code

Why is it that ASP/ASP.NET Response.Redirect uses a HTTP-302 status code ("Moved Temporarily") even though in most cases a HTTP-301 status code ("Moved Permanently") would be more appropriate?

Exceptions: redirect or render?

I m trying to standardize the way I handle exceptions in my web application (homemade framework) but I m not certain of the "correct" way to handle various situations. I m wondering if there is a ...

Cakephp is not redirecting properly when pages are cached

I am having some issues with a site that was working correctly until i implemented full page caching in CakePHP. I have followed the guidance in the Manual and have my $session->flash in a no-cache ...

热门标签