Nodejs:重定向 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6234380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:15:59  来源:igfitidea点击:

Nodejs : Redirect URL

urlredirectnode.js

提问by Adam

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

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

// 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?

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

采纳答案by Geoff Chappell

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 和你的方式差不多。从我所看到的不同之处在于它们推送一些正文内容并使用绝对网址。

See the express response.redirect method:

参见 express response.redirect 方法:

https://github.com/visionmedia/express/blob/master/lib/response.js#L335

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

回答by Kamrul

Yes it should be full url in setHeader.

是的,它应该是setHeader.

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

回答by Brad

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

回答by jcolebrand

What happens if you change it to 307 instead?

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

回答by Rob

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.

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