【问题标题】:Nodejs : Redirect URLNodejs:重定向网址
【发布时间】:2011-09-08 05:29:06
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您是否尝试过在响应正文中发送内容? response.setHeader('Content-Type', 'text/plain'); response.end('<p>302. Redirecting to xxx.com</p>');

标签: url redirect node.js


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    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);
        });
    

    【讨论】:

      【解决方案3】:

      是的,它应该是setHeader 中的完整网址。

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

      【讨论】:

        【解决方案4】:

        如果改为 307 会怎样?

        【讨论】:

        • @CIRK 我当时改了答案。
        【解决方案5】:

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

        【讨论】:

          猜你喜欢
          • 2011-05-03
          • 2010-11-29
          • 1970-01-01
          • 2014-06-08
          • 2017-10-21
          • 2010-12-31
          相关资源
          最近更新 更多