0

我尝试了很多解决方案,但没有一个适合我

我已经安装了 Laravel echo 和 pusher js 和 Pusher/Pusher

#bootstrap.js

import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: true,

});

#.env

BROADCAST_DRIVER=pusher
PUSHER_APP_ID=my_id
PUSHER_APP_KEY=my_key
PUSHER_APP_SECRET=my_secret
PUSHER_APP_CLUSTER=eu

我的事件文件 NewMessage

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->to);
    }
    public function broadcastWith()
    {
        return ["message" => $this->message];
    }
}

频道.php

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

Vue 应用 JS 代码

mounted(){
            Echo.private(`messages${this.user.id}`)
            .listen('NewMessage', (e) => {
                this.handleIncoming(e.message)
            });
          },
methods:{
      saveNewMessage(msg){
                this.messages.push(msg);
            },
            handleIncoming(message){
                if(this.selectedContact && message.from == this.selectedContact.id ){
                    this.saveNewMessage(message);
                    return;
                }
                alert(message.text);
            }
          }

api.php

Route::post('/conversation/send', 'Api\ContactController@sendNewMessage');

联系控制器

public function sendNewMessage(Request $request)
    {
       $message = Message::create([
            'from' => $request->sender_id,
            'to' => $request->receiver_id,
            'text' => $request->text
        ]);

        broadcast(new NewMessage($message));
        return response()->json($message);
    }

我还阅读了官方文档,一切都很好,但我不明白为什么,这是一个抛出错误。有什么想法吗?

4

1 回答 1

0

我弄清楚为什么每次都显示身份验证被禁止或不显示身份验证

解决方案:您需要仔细检查您的 PUSHER_APP_KEY ,因为如果设置不正确,则会出现错误,因为我们的流未与推送器连接

PUSHER_APP_KEY="PUT KEY HERE"

如果您非常确定您的应用程序密钥是正确的,请转到网络选项卡并单击您的推送应用程序密钥,如 e70ewesdsdssew0 如果它显示这样的结果

{"event":"pusher:connection_established","data":"{\"socket_id\":\"131139.31305364\",\"activity_timeout\":120}"}

您的 API 密钥很好,如果它不正确它会显示这样的错误

{"event":"pusher:error","data":{"code":4001,"message":"App key 3fdsfdfsdfsd not in this cluster. Did you forget to specify the cluster?"}}

另外,不要忘记放置集群密钥

PUSHER_APP_CLUSTER=eu
于 2021-01-02T06:18:46.633 回答