节点应用程序:Http到httpsredirect不适用于本地主机

我将HTTPS添加到node.js应用程序,同时将HTTP转发到HTTPS。 我正在使用下面的代码:

  // Trusting proxy self.app.enable('trust proxy'); // Http -> Https redirection middleware self.app.use(function (req, res, next) { var schema = req.protocol.toLowerCase(); console.log("Redirection check, schema: " + schema); if (schema === 'https') { console.log("Next"); next(); } else { var tmp = 'https://' + req.headers.host + req.url; console.log("Redirect to: " + tmp); res.redirect(tmp); } }); 

当我浏览https://localhost:8443/index.html ,所有工作正常,页面打开罚款。

但是,当我尝试http://localhost:8443/index.html ,Chrome似乎redirect或重写URL为localhost:8443/index.html和Chrome等待本地主机永远。 我的应用程序没有控制台消息。 我在Windows 7下使用Chrome。

我的代码有什么问题?

Chrome只是隐藏了URL的http://部分,这是正常的。

您不能在同一个端口上运行httphttps

您在地址中指定了http ,因此浏览器尝试使用HTTP进行连接。 服务器正在侦听HTTPS,因此失败。