【问题标题】:Node JS redirection loopNode JS 重定向循环
【发布时间】:2016-09-07 06:17:52
【问题描述】:

我有这段代码:

app.get('/*', function(req, res, next) {
    res.redirect(301, 'http://example.com' + req.path);
});

chrome 写错误:

“example.com 页面无法正常工作

example.com 重定向您的次数过多。”

有什么想法吗?

【问题讨论】:

  • 为什么期望它停止重定向?
  • 在您的示例中,http://example.com 是您服务器的主机名吗?换句话说:您是否正在重定向到您自己的服务器?
  • 看起来像无限循环...
  • 目标是从 www.example.com 重定向到 example.com 或从 example.net 重定向到 example.com
  • 然后根据主机进行有条件的重定向。

标签: javascript node.js express redirect routing


【解决方案1】:

您的代码总是会重定向您。

您需要添加主机检查条件。

例如:

app.get('/*', function(req, res, next) {
   if (/^www\./.test(req.headers.host)) {
     res.redirect(301, 'http://example.com' + req.path);
   }
});

【讨论】:

    猜你喜欢
    • 2017-02-06
    • 2021-03-18
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 2017-12-22
    • 1970-01-01
    相关资源
    最近更新 更多