【问题标题】:Laravel Echo listener is not listeningLaravel Echo 监听器没有在听
【发布时间】:2020-08-30 05:43:09
【问题描述】:

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

Database Tables and Relations

我想为每个可用的团队创建一个私人频道。 一旦您单击群聊,就会加载并显示现有消息。 当您发送消息时,该消息将被添加到消息表中并成功发送到推送器,如下所示: 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>

应用程序/事件/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');
}
}

联系人控制器

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

【问题讨论】:

  • 你在 bootstraps.js 中配置了 laravel echo 吗?
  • 是的,否则推送者不会收到请求。
  • 我在问题中添加了 bootstrap.js。
  • 尝试将加密设置为false?
  • 现在可以使用了。将 encrypted 设置为 false 解决了该问题。谢谢@UzairRiaz

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


【解决方案1】:

encrypted 设置为 true 用于 SSL 配置。在bootstrap.js配置laravel echo时尝试设置为false

【讨论】:

    【解决方案2】:

    正如您在 cmets 中看到的,在 bootstrap.js 中将 encrypted 设置为 false 解决了问题

    【讨论】:

    • 我会把它作为答案发布,您可以接受它,以便对其他人有所帮助。
    猜你喜欢
    • 2022-06-21
    • 2020-08-22
    • 2021-05-02
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 2019-09-21
    • 2017-08-21
    • 2020-09-17
    相关资源
    最近更新 更多