You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React/TypeScript前端无法通过Laravel Echo接收Laravel Reverb事件

问题排查与解决方案

核心问题分析

Reverb终端仅收到pusher:ping说明前后端连接正常,但事件未从后端推送至Reverb,或频道订阅/事件监听存在配置错误。

分步排查

  1. 后端事件广播配置检查

    • 确认.env广播驱动设置为reverb:BROADCAST_DRIVER=reverb
    • 确保.env中REVERB_APP_ID、REVERB_APP_KEY、REVERB_APP_SECRET前后端完全一致,同时设置REVERB_HOST=127.0.0.1、REVERB_PORT=8001
    • 验证事件类实现ShouldBroadcast接口,且broadcastOn()返回正确频道实例:公开频道用BroadcastChannel('public-channel'),私有频道用PrivateChannel('private-user.' . $this->user->id)
  2. 事件推送验证

    • 在控制器中手动触发事件:event(new YourEvent($data))
    • 查看Reverb调试终端,成功推送会显示Message Sent日志,包含事件名称与频道;无日志则检查事件类broadcastOn逻辑或构造函数数据传递
  3. 私有频道认证修正

    • 你的认证端点指向Reverb服务(8001)是错误的,私有频道认证需请求Laravel API(8080),调整Echo配置:
      const echo = new Echo({
        broadcaster: 'reverb',
        key: import.meta.env.VITE_REVERB_APP_KEY,
        wsHost: 'localhost',
        wsPort: 8001,
        forceTLS: false,
        enabledTransports: ['ws', 'wss'],
        auth: {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`,
          },
          endpoint: 'http://localhost:8080/api/broadcasting/auth',
        },
      });
      
    • 检查routes/channels.php授权逻辑,确保返回正确判断:
      Broadcast::channel('private-user.{userId}', function ($user, $userId) {
          return (int) $user->id === (int) $userId;
      });
      
    • 确认前端携带有效认证令牌(JWT/Session),Laravel能正确识别用户
  4. 前端监听正确性检查

    • 监听频道名称需与后端一致,私有频道要加private-前缀:
      echo.private('private-user.1')
        .listen('YourEventName', (e) => {
          console.log('Received event:', e);
        });
      
    • 查看浏览器控制台,排查认证失败、频道不存在等错误

Laravel Reverb + React TS + Laravel API 分步搭建指南

一、Laravel后端API配置

  1. 安装Reverb
    composer require laravel/reverb
    php artisan reverb:install
    
  2. 配置环境变量
    在.env中添加:
    BROADCAST_DRIVER=reverb
    REVERB_APP_ID=自定义ID
    REVERB_APP_KEY=自定义密钥
    REVERB_APP_SECRET=自定义秘钥
    REVERB_HOST=127.0.0.1
    REVERB_PORT=8001
    REVERB_SCHEME=http
    
  3. 配置广播路由
    在routes/api.php中添加(Laravel 11默认已包含,可根据认证方式调整中间件):
    use Illuminate\Support\Facades\Broadcast;
    
    Broadcast::routes(['middleware' => ['auth:sanctum']]);
    
  4. 创建事件类
    php artisan make:event UserNotification
    
    修改事件类:
    namespace App\Events;
    
    use Illuminate\Broadcasting\PrivateChannel;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\InteractsWithSockets;
    use Illuminate\Queue\SerializesModels;
    
    class UserNotification implements ShouldBroadcast
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
    
        public $message;
        public $userId;
    
        public function __construct(string $message, int $userId)
        {
            $this->message = $message;
            $this->userId = $userId;
        }
    
        public function broadcastOn(): PrivateChannel
        {
            return new PrivateChannel('private-user.' . $this->userId);
        }
    
        public function broadcastAs(): string
        {
            return 'user.notification';
        }
    }
    
  5. 频道授权配置
    在routes/channels.php中添加:
    Broadcast::channel('private-user.{userId}', function ($user, $userId) {
        return (int) $user->id === (int) $userId;
    });
    

二、启动Reverb服务

php artisan reverb:start --host=127.0.0.1 --port=8001 --debug

三、React TS前端配置

  1. 安装依赖
    npm install laravel-echo pusher-js
    
  2. 创建Echo实例
    在src/utils/echo.ts中:
    import Echo from 'laravel-echo';
    import Pusher from 'pusher-js';
    
    window.Pusher = Pusher;
    
    const echo = new Echo({
      broadcaster: 'reverb',
      key: import.meta.env.VITE_REVERB_APP_KEY,
      wsHost: import.meta.env.VITE_REVERB_HOST,
      wsPort: parseInt(import.meta.env.VITE_REVERB_PORT || '8001'),
      forceTLS: false,
      enabledTransports: ['ws', 'wss'],
      auth: {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('auth_token')}`,
        },
        endpoint: `${import.meta.env.VITE_API_URL}/api/broadcasting/auth`,
      },
    });
    
    export default echo;
    
  3. 添加环境变量
    在.env中:
    VITE_REVERB_APP_KEY=自定义密钥(与后端一致)
    VITE_REVERB_HOST=localhost
    VITE_REVERB_PORT=8001
    VITE_API_URL=http://localhost:8080
    
  4. 组件中监听事件
    import { useEffect } from 'react';
    import echo from './utils/echo';
    
    function NotificationComponent() {
      useEffect(() => {
        const userId = 1; // 替换为当前登录用户ID
        const channel = echo.private(`private-user.${userId}`);
    
        channel.listen('.user.notification', (data) => {
          console.log('收到通知:', data.message);
        });
    
        return () => {
          channel.stopListening('.user.notification');
        };
      }, []);
    
      return <div>监听通知中...</div>;
    }
    
    export default NotificationComponent;
    

四、测试事件广播

在Laravel控制器中添加触发方法:

use App\Events\UserNotification;

public function sendNotification()
{
    event(new UserNotification('你有一条新消息', 1));
    return response()->json(['message' => '事件已发送']);
}

调用该接口后,查看Reverb终端的事件日志与前端控制台的接收数据。


内容的提问来源于stack exchange,提问作者Adeolu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 21:54:51