除了 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/