1

学习Laravel事件广播//EchoVue这个教程

我不断收到对身份验证的响应,我怀疑我对路由403缺乏了解是问题所在。channels.php我正在使用Player模型而不是可以正常User工作的模型Auth

事件ChatMessageSend

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

    public $channel;
    public $player;
    public $chatMessage;

        /**
         * Create a new event instance.
         * GameChat constructor.
         * @param $chatMessage
         * @param $player
         */
        public function __construct(ChatMessage $chatMessage, Player $player)
        {
            $this->channel = session()->get('chat.channel');

            $this->chatMessage = $chatMessage;

            $this->player = $player;
        }

        /**
         * Get the channels the event should broadcast on.
         *
         * @return Channel|array
         */
        public function broadcastOn()
        {
            return new PrivateChannel($this->channel);
        }
    }

监听器ChatMessageNotification(默认/空)

class ChatMessageNotification
{
    /**
     * ChatMessageNotification constructor.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ChatMessageSent  $event
     * @return void
     */
    public function handle(ChatMessageSent $event)
    {
        //
    }
}

控制器ChatController

class ChatController extends Controller
{
    /**
     * Send chat message
     *
     * @param Request $request
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getMessages(Request $request)
    {
        return ChatMessage::with('player')
            ->where('progress_id', '=', session('game.progress.id'))
            ->orderBy('created_at', 'DESC')
            ->get();
    }

    /**
     * Send chat message
     *
     * @param Request $request
     * @return array|string
     */
    public function sendMessage(Request $request)
    {
        $player = Auth::user();

        $message = $request->input('message');

        if ($message) {
            $message = ChatMessage::create([
                'player_id'   => $player->id,
                'progress_id' => session()->get('game.progress.id'),
                'message'     => $request->input('message')
            ]);
        }

        broadcast(new ChatMessageSent($player, $message))->toOthers();

        return ['type' => 'success'];
    }
}

路线channels.php

Broadcast::channel(session()->get('chat.channel'), function ($player, $message) {
    return $player->inRoom();
});

在我的Player课堂上

/**
 * A user can be in one chat channel
 */
public function inRoom()
{
    if ((Auth::check()) and ($this->games()->where('progress_id', '=', session('game.progress.id'))->get())) {
        return true;
    }

    return false;
}

当玩家登录时,我会在会话中存储一个我想用作频道的聊天室 ID。

我的vue聊天实例是

Vue.component('chat-messages', require('./../generic/chat-messages.vue'));
Vue.component('chat-form', require('./../generic/chat-form.vue'));

const app = new Vue({
    el: '#toolbar-chat',

    data: {
        messages: []
    },

    created() {
        this.fetchMessages();

        Echo.private(chat_channel)
        .listen('chatmessagesent', (e) => {
            this.messages.unshift({
                message: e.data.message,
                player: e.data.player.nickname
            });
        });
    },

    methods: {
        fetchMessages() {
            axios.get(chat_get_route)
            .then(response => {
                this.messages = response.data;
            });
        },

        addMessage(message) {
            this.messages.unshift(message);

            this.$nextTick(() => {
                this.$refs.toolbarChat.scrollTop = 0;
            });

            axios.post(chat_send_route, message)
            .then(response => {
                console.log(response.data);
            });

        }
    }
});

但我不断得到

POST http://my-games.app/broadcasting/auth 403 (Forbidden)
Pusher : Couldn't get auth info from your webapp : 403
4

3 回答 3

3

错误 403 /broadcasting/auth with Laravel version > 5.3 & Pusher,你需要在resources/assets/js/bootstrap.js中更改你的代码

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your key',
    cluster: 'your cluster',
    encrypted: true,
    auth: {
        headers: {
            Authorization: 'Bearer ' + YourTokenLogin
        },
    },
});

并在app/Providers/BroadcastServiceProvider.php更改为

Broadcast::routes()

Broadcast::routes(['middleware' => ['auth:api']]);

或者

Broadcast::routes(['middleware' => ['jwt.auth']]); //if you use JWT

它对我有用,希望对你有帮助。

于 2018-05-18T07:18:29.123 回答
0

弄清楚您的 routes/channels.php 文件是否按预期运行可能是一个想法。也许添加一些日志以查看该路由是否被调用,并且您的 inRoom 函数正在返回您所期望的。

于 2017-08-14T11:15:36.353 回答
0

如果有人仍然需要答案,这对我有用。添加到您的 broadcastServiceProvider.php

Broadcast::routes([
'middleware' => 'auth:api']);

添加到您的 channels.php

Broadcast::channel('chat', function () {
    return Auth::check();
});
于 2020-04-21T11:50:21.807 回答