部署在Railway的Django WebSocket无法通过HTTPS连接求助
当项目部署到HTTPS环境的Railway平台后,WebSocket无法正常工作,控制台抛出以下两个错误:
Mixed Content: The page at 'https://supreme-key-production.up.railway.app/rooms/bangladesh_ott/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://supreme-key-production.up.railway.app/ws/bangladesh_ott/'. This request has been blocked; this endpoint must be available over WSS.
Uncaught DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.
at window.onload (https://supreme-key-production.up.railway.app/rooms/bangladesh_ott/:382:24)
问题原因
HTTPS页面出于安全限制,不允许发起非加密的WebSocket(ws://)连接,必须使用加密的WebSocket协议(wss://)。你的代码硬编码了ws://协议,导致在HTTPS环境下被浏览器拦截。
解决方案
修改前端代码,根据当前页面的协议动态选择WebSocket协议,实现本地HTTP环境和线上HTTPS环境的自动适配:
window.onload = function() { const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const userName = JSON.parse(document.getElementById('json-username').textContent); // 根据当前页面协议自动选择ws/wss const wsProtocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://'; const chatSocket = new WebSocket( wsProtocol + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onmessage = function(e) { console.log('onmessage') const data = JSON.parse(e.data); if (data.message) { let html = '<div class="message">'; html += '<p class="messsage_username">' + data.username + '</p>'; html += '<p class="message_message">' + data.message + '</p></div>'; document.querySelector('#chat-messages').innerHTML += html; } else { alert('The message was empty!'); } } chatSocket.onclose = function(e) { console.log('onclose') } document.querySelector('#chat-message-submit').onclick = function(e) { e.preventDefault(); const messageInputDom = document.querySelector('#chat-message-input'); const message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'message': message, 'username': userName, 'room': roomName })); messageInputDom.value = ''; return false; } }
说明
通过window.location.protocol判断当前页面使用的是HTTP还是HTTPS协议:
- 若为HTTPS,则使用
wss://发起加密WebSocket连接 - 若为HTTP(本地开发环境),则使用
ws://保持原有逻辑
这样修改后,项目在本地和线上HTTPS环境都能正常建立WebSocket连接。
内容的提问来源于stack exchange,提问作者Ayat Rahman

