heroku - 在 Heroku 上使用 Daphne 的 Websocket 握手期间出错,错误代码为 500
问题描述
所以我尝试将我的 docker django 聊天应用程序部署到 heroku。以前我一直使用 runserver 命令运行应用程序,但现在我切换到 daphne,因为我需要使用 websocket,但我不能再使用 runserver 来连接到 webserver。部署后,当我访问显示聊天窗口的应用程序页面时,会发生此错误
WebSocket connection to 'wss://xxx.herokuapp.com/ws/chat/room/' failed: Error during WebSocket handshake: Unexpected response code: 500
(xxx实际上是我的应用程序的网址)
这是我的一段js代码
<script>
var roomName = "{{ room_name|escapejs }}";
var wsStart = 'ws://';
if (window.location.protocol === 'https:') {
wsStart = 'wss://';
}
var chatSocket = new WebSocket(
wsStart + window.location.host +
'/ws/chat/' + roomName + '/');
chatSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
var message = data['message'];
document.querySelector('#chat-log').value += (message + '\n');
};
ws 没有工作(错误消息 Django 只能使用 ASGI 而不是 websocket)所以我改为 wss(根据 stackoverflow 中的另一篇文章这是因为安全原因),这使得另一个错误消失但仍然无法连接到 websocket
这是我的运行命令:
daphne -p $PORT --bind 0.0.0.0 -v2 test_project.asgi:application
编辑:如果我不使用 wss(只使用 ws 代替)这是 js 控制台中的错误消息
The page at 'https://xxx/chat/m/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://xxx/ws/chat/room/'. This request has been blocked; this endpoint must be available over WSS.
非常感谢任何帮助,或出错的想法。太感谢了!
解决方案
事实证明,它与 daphne 或我的 js 代码不起作用几乎没有关系。当时我没有连接到heroku-redis,因此没有运行redis。配置 REDISTOGO_URL 与
heroku config --app <appname> | grep REDISTOGO_URL
,将channel_layer中的主机从"hosts": ('redis', 6379),
(类似的东西)更改为"hosts": [os.environ.get('REDISTOGO_URL',('redis', 6379))]
允许我连接到heroku redis。
推荐阅读
- java - 解析多个 picocli(子)命令和 shell
- excel - 如何在 Excel 中考虑重复值时从两列中查找不匹配的记录
- python - Python:从带有条件的字典中附加一个列表
- javascript - TextDecoder.prototype.ignoreBOM 未按预期工作
- html - 如何减少wordpress中的边距?
- javascript - 如果在 React (JSX) 中编写多行
- python - 如何在特定坐标/小部件处添加 Python Kivy Touch Ripple?
- python - 将 django 模型类导入 Plotly-Dash 无状态应用程序
- python - 如何使用python摆脱重复链接
- c# - 无法在 UAT 环境中解析日期,但在我的本地工作