javascript - Node 应用: Http to Https redirection does not work for localhost

标签 javascript node.js redirect https

我正在将 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 似乎将 url 重定向或重写为 localhost:8443/index.html 并且Chrome 永远等待本地主机。我的应用程序没有控制台消息。我在 Windows 7 下使用 Chrome。

我的代码有什么问题?

最佳答案

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

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

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

关于javascript - Node 应用: Http to Https redirection does not work for localhost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25624742/

相关文章:

C++ 忽略某些输出的 cout 重定向

javascript - “onclick”存储值不起作用

javascript - 从 native Webview 获取网页的动态内容

javascript - 如何在preact中创建辅助(高阶组件)?

javascript - 使用 .then 函数时页面未加载

ruby-on-rails - 如何重定向到页面中的特定位置?

javascript - 我如何使用 jQuery 在 HTML 标记中选择和排序字符?

node.js - NodeJS + Express : How to secure a URL

node.js - 来自 Angular ngResource-Service 的 REST-API 调用未由反向代理转发

php header 位置马上?