Nodejs:重定向 URL

问题描述:

我正在尝试以这种方式在 node.js 中重定向我的应用程序的 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.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.

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

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

看起来 express 和你的方式差不多.从我所看到的不同之处在于它们推送一些正文内容并使用绝对网址.

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.

查看 express response.redirect 方法:

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