反应js前端无法收听laravel pusher后端的私有频道

时间:2018-09-21 08:54:37

标签: reactjs laravel

我没有问题,可以让laravel在公共频道播放,外部反应在公共频道上反应良好。切换到专用频道后,laravel会以302重定向进行响应。

感谢任何帮助。

反应代码:

subscribeToPrivateChannel = (userId) => {
this.pusher = new Pusher('something', {
  broadcaster: 'pusher',
  appId: 'appid',
  key: 'key',
  secret: 'secret',
  cluster: 'cluster',
  authEndpoint: 'http://localhost:8000/broadcasting/auth'
})
this.channel = this.pusher.subscribe(`private-notification_${userId}`)

this.channel.bind('created', this.updateNotifications)
this.channel.bind('updated', this.updateNotifications)
this.channel.bind('deleted', this.updateNotifications)
this.channel.bind('App\\Events\\PushNotification', this.updateNotifications)

console.log("THIS PUSHER: ", this.pusher)
console.log("THIS CHANNEL: ", this.channel)
}

在laravel BroadcastServiceProvider.php内部:

public function boot()
{
    Broadcast::routes(['middleware' => 'auth:api']);

    require base_path('routes/channels.php');
}

在channels.php内部:

Broadcast::channel('notification_{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});

当我从BroadcastServiceProvider.php路由中删除['middleware'=>'auth:api']时,laravel禁止使用403。

1 个答案:

答案 0 :(得分:0)

在反应代码中添加承载令牌:

this.pusher = new Pusher('something', {
  broadcaster: 'pusher',
  appId: 'appid',
  key: 'key',
  secret: 'secret',
  cluster: 'cluster',
  auth:{
    headers:{
      'Accept':'application/json',
      'Authorization': 'Bearer ' + getToken()
    }
  }
  authEndpoint: 'http://localhost:8000/broadcasting/auth'
})