Laravel Echo监听器未监听

时间:2020-05-13 20:55:33

标签: node.js laravel vue.js pusher laravel-echo

这是我的第一个使用vue和nodejs的项目,所以如果我缺少信息,请告诉我。 我正在尝试与Laravel,Vue js和Pusher建立群聊。

Database Tables and Relations

我想为每个可用的团队创建一个私人频道。 一旦您单击群聊,就会加载并显示现有消息。 当您发送消息时,该消息将被添加到消息表中,并且还可以成功发送到pusher,如下所示: Pusher message

该消息还会添加到发件人的消息列表中,但不会添加到其他团队成员上。

Sender

Other team members

新消息仅在其他团队成员重新加载页面时显示。这意味着回声监听器似乎不起作用。我该如何解决?怎么了?

这是我的代码:

ChatApp.vue(根组件)

<template>
<div class="chat-container row">
    <i class="far fa-comments fa-3x"></i>
    <div id="chat-app" class="chat-app">
        <div class="row mx-0 h-100 overflow-hidden">
            <TeamList :teams="teamList" @selected="startConversationWith"/>
            <Conversation :team="selectedTeam" :messages="messages" @new="saveNewMessage"/>
        </div>
    </div>
</div>
</template>

<script>
import MessageList from './MessageList';
import TeamList from './TeamList';
import Conversation from './Conversation';
import MessageTextBox from './MessageTextBox';

export default {
    props: {
        user: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            messages: [],
            teamList: [],
            selectedTeam: null,
        }
    },
    mounted() {
        Echo.private('messages.1')
            .listen('NewMessage', (e) => {
                this.handleIncoming(e.message);
            });

        axios.get('/teams')
            .then((response) => {
                this.teamList = response.data;
            });
    },
    methods: {
        startConversationWith(team) {
            axios.get('/conversation/' + team.id)
                .then((response) => {
                    this.messages = response.data;
                    this.selectedTeam = team;
                });
        },
        saveNewMessage(text) {
            this.messages.push(text);
        },
        handleIncoming(message) {
            this.saveNewMessage(message);
            return;
        }
    },
    components: {TeamList, MessageList, MessageTextBox, Conversation}
}
</script>

App / Events / NewMessage.php

<?php

namespace App\Events;

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

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

public $message;

/**
 * Create a new event instance.
 *
 * @param Message $message
 */
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->team_id);
}

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

routes / channels.php

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('messages.{id}', function ($team_id, $message) {
return true;
//    return (int) $team->id === (int) $id;
});

消息模型

namespace App;
use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
protected $guarded = [];

public function team()
{
    return $this->belongsTo('App\Team');
}

public function user()
{
    return $this->belongsTo('App\User');
}
}

ContactsController

namespace App\Http\Controllers;

use App\Events\NewMessage;
use App\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;

class ContactsController extends Controller
{

public function getTeams() {
    $teams = Auth::user()->teams;
    return response()->json($teams);
}


public function getMessagesFor($id)
{
    $messages = Message::where('team_id', $id)->get();
    return response()->json($messages);
}

public function send(Request $request) {
    $message = Message::create([
        'team_id' => $request->team_id,
        'user_id' => Auth::user()->id,
        'message' => $request->text
    ]);
    broadcast(new NewMessage($message));
    return response()->json($message);
}
}

bootstrap.js

window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
*/

try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');

require('bootstrap');
} catch (e) {}

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
*/

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
*/

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
});

2 个答案:

答案 0 :(得分:1)

对于SSL配置,

encrypted设置为true。在false中配置laravel echo时,请尝试将其设置为bootstrap.js

答案 1 :(得分:0)

您可以在评论中看到,在bootstrap.js中将加密设置为false可以解决问题