0

I'm using pusher for push notifications in my laravel production web with cloud server. It's was working on localhost, then stopped working on localhost too and giving the error in console that channel is not defined.

Header:

<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" type="text/css"
      href="//cdn.jsdelivr.net/npm/bootstrap-notifications@1.0.3/dist/stylesheets/bootstrap-notifications.min.css">

Body:

<script>

    var notificationsWrapper = $('.dropdown');
    var notificationsToggle = notificationsWrapper.find('a[data-toggle]');
    var notificationsCountElem = notificationsToggle.find('i[data-count]');
    var notificationsCount = parseInt(notificationsCountElem.data('count'));
    var notifications = notificationsWrapper.find('ul.dropdown-menu');

    if (notificationsCount <= 0) {
        notificationsWrapper.hide();
    }

    // Enable pusher logging - don't include this in production
    // Pusher.logToConsole = true;

    const pusher = new Pusher('PUSHER_APP_KEY', {
        cluster: 'ap2',
        encrypted: true
    });

    // Bind a function to a Event (the full Laravel class)
    channel.bind('App\\Events\\StatusLiked', function (data) {
        var existingNotifications = notifications.html();
        var avatar = Math.floor(Math.random() * (71 - 20 + 1)) + 20;
        var newNotificationHtml = "" +
            "<li class='notification active'><div class='media'>" +
            "<div class='media-left'>" +
            "<div class='media-object'>" +
            "<img src='https://api.adorable.io/avatars/71/" + avatar + ".png' class='img-circle' alt='50x50' style='width: 50px; height: 50px;'>" +
            "</div>" +
            "</div>" +
            "<div class='media-body'>" +
            "<strong class='notification-title'>" + data.message + "</strong><!--p class='notification-desc'>Extra description can go here</p-->" +
            "<div class='notification-meta'>" +
            "<small class='timestamp'>about a minute ago</small>" +
            "</div>" +
            "</div>" +
            "</div>" +
            "</li>";
        notifications.html(newNotificationHtml + existingNotifications).trigger('create');

        notificationsCount += 1;
        notificationsCountElem.attr('data-count', notificationsCount);
        notificationsWrapper.find('.notif-count').text(notificationsCount);
        notificationsWrapper.show();
    });
</script>

The console prints Channel is is not defined.

4

1 回答 1

1

在绑定到频道上的事件之前,您需要订阅频道。Channels 流程是: 1. 连接到 Channels 服务 2. 订阅频道 3. 绑定到订阅频道上的事件。

由于您没有在 Pusher 对象中包含 Auth URL 参数,我可以假设您正在使用公共频道。您可以使用以下方式订阅公共频道:

var channel = pusher.subscribe('CHANNEL-NAME');

注意:任何已发布的事件都会发布到频道,因此您需要确保您在客户端上订阅的频道与您从服务器发布事件的频道相匹配。

于 2020-06-12T08:08:08.203 回答