在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.

非常感谢您提供的任何帮助或对出现问题的想法。非常感谢!

sarah928 回答:在Heroku上使用Daphne进行Websocket握手时出错,错误代码为500

原来,它与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。

本文链接:https://www.f2er.com/2687232.html

大家都在问