html - 可以从 http 进行 https 重定向吗?

标签 html node.js http https socket.io

除了 postgresql 数据库外,我还有一个使用 node.js 和 socket.io 库的 Web 应用程序。它托管在 heroku 上。对于 socket.io 库,如果我使用输入为“http://X”的站点地址运行我的代码,但在我尝试“https://X”时不会收到错误消息 为了修复这个错误,如果用户访问 http 版本,我会强制将用户重定向到 https 站点。这是我执行此操作的代码。

<script>
  if (document.URL.indexOf("https") == -1 && document.URL.indexOf("localhost") == -1)
  {
    window.location.href = document.URL.replace("http", "https");
  }
</script> 

为什么这是个坏主意?有更好的解决方案吗?如果您对 http 和 https 之间的区别有任何评论,我们将不胜感激。这是我在 http 上运行网站时遇到的错误:

WebSocket connection to 'ws://theland.herokuapp.com/socket.io/?EIO=3&transport=websocket&sid=<not sure if I should share this part of the url...>' failed: Error during WebSocket handshake`: 'Sec-WebSocket-Accept' header is missing

需要澄清的是,该网站现在可以很好地使用我的解决方案,但我担心我的解决方案是否是“良好做法”。

感谢您的帮助!

最佳答案

在客户端,包含没有 URL 的 Socket.IO 就足够了:

<script src="/socket.io/socket.io.js"></script>
<script> const socket = io(); </script>

另一种选择是将 URL 用于:

wss://yourURL

如果这不起作用,更好的方法是从服务器端重定向,例如:

app.get('/anyURL', (req, res) => {

    if (req.headers.host.match(/^www/) !== null || !req.secure) {
        return res.redirect('https://' + req.headers.host.replace(/^www\./, '') + req.url);
    };
});

关于html - 可以从 http 进行 https 重定向吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808069/

相关文章:

jquery - 如何检查数组是否包含具有相同文本的字符串?

javascript - Mongoose 和人口嵌套

java - 通过 urlconnect 进行 Kerberos 凭证委托(delegate)?

angular - 将生成的 forkJoin 数组传递给 Angular 中的多个组件

java - 如何用 Java 向 Octoprint 发送 POST 请求?

javascript - 如何使用 jquery 应用条件逻辑

html - 我如何通过 svn 提供 html? (svn 可以充当网络服务器吗?)

html - 如何更改用于文本的 <u> 标签的颜色属性

node.js - Node - 生成 AES-CBC key 和 iv

javascript - 如何在 node.js 中终止的 http 连接上干净地关闭 FD