简体   繁体   English

节点应用程序:Http到Https重定向不适用于localhost

[英]Node application: Http to Https redirection does not work for localhost

I am adding HTTPS to a node.js application, while forwarding HTTP to HTTPS. 我将HTTPS添加到node.js应用程序,同时将HTTP转发到HTTPS。 I am using the following bit of code: 我正在使用以下代码:

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

    });

All works fine when I browse https://localhost:8443/index.html , the page opens fine. 当我浏览https://localhost:8443/index.html ,一切正常,页面打开正常。

But when I try http://localhost:8443/index.html , Chrome seems to redirect or rewrite the url to localhost:8443/index.html and Chrome waits for localhost eternally. 但是,当我尝试http://localhost:8443/index.html ,Chrome似乎将URL重定向或重写为localhost:8443/index.html并且Chrome永远等待localhost。 There is no console message from my application. 我的应用程序没有控制台消息。 I am on under windows 7 with Chrome. 我在Windows 7下使用Chrome。

What is wrong with my code? 我的代码有什么问题?

Chrome is just hiding the http:// portion of the URL, this is normal. Chrome只是隐藏http://部分,这是正常的。

You can't run http and https on the same port. 您不能在同一端口上运行httphttps

You've specified http in the address, so the browser tries to connect with HTTP. 您在地址中指定了http ,因此浏览器尝试使用HTTP连接。 The server is listening for HTTPS so it fails. 服务器正在监听HTTPS,因此失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM