reactjs - laravel-echo 如何与 Pusher 和 React JS 一起工作?

标签 reactjs laravel pusher

我使用 Laravel Passport 创建了 REST API,并将它们放在我的子域中,即“api.abc.com”。我有一个连接到它的 React js 应用程序。现在,为了添加实时消息传递,我使用了“pusher”和“laravel echo”。

React 应用程序可以成功连接到推送器,我每次都可以在调试控制台上看到这一点。在我发送消息的地方,它也会存储在数据库和推送器中。但相应的 laravel echo channel 监听器没有被触发。我已经尝试了所有变体,但无法使其发挥作用。

REST API 放置在服务器上,React APP 当前托管在本地。这就是为什么我将“加密”设置为“假”。

APP//事件//新消息


use App\Message;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Message $message)
    {
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('messages.' .  $this->message->conversation_id);
    }

    public function broadcastWith()
    {
        return ["message" => $this->message];
    }

    public function broadcastAs()
    {
        return 'chat';
    }
}

在消息存储函数内注册事件

broadcast(new NewMessage($msg));

配置//广播.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Broadcaster
    |--------------------------------------------------------------------------
    |
    | This option controls the default broadcaster that will be used by the
    | framework when an event needs to be broadcast. You may set this to
    | any of the connections defined in the "connections" array below.
    |
    | Supported: "pusher", "redis", "log", "null"
    |
    */

    'default' => env('BROADCAST_DRIVER', 'null'),

    /*
    |--------------------------------------------------------------------------
    | Broadcast Connections
    |--------------------------------------------------------------------------
    |
    | Here you may define all of the broadcast connections that will be used
    | to broadcast events to other systems or over websockets. Samples of
    | each available type of connection are provided inside this array.
    |
    */

    'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                'encrypted' => false,
            ],
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

];

路线//channels.php

<?php

use App\Conversation;

/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/

Broadcast::channel('messages.{id}', function ($user, $id) {
    $con = Conversation::findOrFail($id);
    // return $user->id == $con->user_id || $user->id == $con->shop_owner_id;
    return true;
});

来 self 的 REACT 应用

import Pusher from "pusher-js";
import Echo from "laravel-echo";
import Cookies from "universal-cookie";

const cookies = new Cookies();

const options = {
    broadcaster: "pusher",
    key: "d4b9af39550bd7832778",
    cluster: "ap2",
    forceTLS: true,
    encrypted: false,
    //authEndpoint is your apiUrl + /broadcasting/auth
    authEndpoint: "https://api.abc.com/broadcasting/auth",
    // As I'm using JWT tokens, I need to manually set up the headers.
    auth: {
        headers: {
            "X-CSRF-TOKEN": csrf_token,
            Authorization: "Bearer " + cookies.get("access_token"),
            Accept: "application/json"
        }
    }
};

const echo = new Echo(options);

在 selectConversation 函数中,我有以下代码

echo.private("messages." + id).listen(".chat", data => {
            console.log("rumman");
            console.log(data);
        });

我还有以下内容:

echo.private("private-messages." + id).listen(".chat", data => {
            console.log("rumman");
            console.log(data);
        });

但我始终无法看到任何 console.log 数据。

最佳答案

ShouldBroadcast 更改为 ShouldBroadcastNow

您的消息正在排队。

关于reactjs - laravel-echo 如何与 Pusher 和 React JS 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56615440/

相关文章:

Laravel 5.4 - 访问 Controller 方法内的静态方法

laravel - 删除 Laravel 6/7 中的相关模型

laravel - 使用 Vue 和 Laravel API 的 Pusher 无法正常工作

laravel - 使用 laravel5.2、vue.js 和 pusher 实时获取数据

javascript - 如何保持 Pusher Client 对象跨页面持久化?

javascript - 子组件在 POST 请求后不重新渲染父组件

reactjs - React Router v6 - 访问嵌套路由和处理手写 url 的正确方法

mysql - 包括相关模型表中的特定列

javascript - typescript 错误 : Cannot redeclare block-scoped variable 'fetch'

node.js - 在多个项目中使用相同模型的最佳实践是什么?