【发布时间】:2020-04-26 14:11:23
【问题描述】:
我正在使用与 Laravel 后端分开托管的 NuxtJS。为了对用户进行身份验证,我使用 Laravel Passport。我正在尝试使用@nuxtjs/laravel-echo 和pusher-js 为我的网站构建聊天功能。这是来自包beyondcode/laravel-websockets 的自托管websocket,使用php artisan websockets:serve 运行。例如,我使用了这个 repo https://github.com/qirolab/Laravel-WebSockets-Chat-Example。只有我使用 Laravel-Passport 和 NuxtJS 的区别
这是我的nuxt.config.js'buildModules` 部分
buildModules: [
...
[
'@nuxtjs/laravel-echo',
{
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: false,
wsHost: process.env.WEBSOCKET_BASE_URL,
wsPort: 6001,
disableStats: true
}
]
],
echo: {
authModule: true,
connectOnLogin: true,
disconnectOnLogout: true
},
我在 Laravel (App\Events\ChatMessageSent.php) 中的活动如下所示:
<?php
namespace App\Events;
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;
use App\ChatMessages;
class ChatMessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public function __construct(ChatMessages $message)
{
$this->message = $message;
}
public function broadcastOn()
{
return new PrivateChannel('chat.' . $this->message->room->id);
}
}
目前我没有过滤用户,所以我的channel.php 有这个条目:
.....
Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
return true;
});
并且该事件将被调度为(我现在没有使用..->toOthers()):
...
broadcast(new ChatMessageSent($message));
...
我的当前用户在我的 NuxtJS 应用程序中经过身份验证,可通过this.$auth.user 获得
在我拥有的前端文件中:
mounted:{
const channel = `chat.${this.roomID}`
this.$echo.private(channel).listen('ChatMessageSent', event => {
console.log(
'-------------------- This is happening!! -----------------------'
)
console.log(event)
this.messages.push(event.message)
})
但应用程序在所有 ChatMessageSent 事件上保持完全安静。根本没有控制台日志。如果我将其切换到公共频道,那么一切正常。我的猜测是身份验证有问题。
在websocket.php 配置文件中,我使用的是api 中间件
*/
'middleware' => [
'api',
Authorize::class,
],
有没有办法在 websocket 上调试身份验证过程?
顺便说一句,我在调试控制台http://localhost:8000/laravel-websockets 中没有看到任何有关身份验证尝试的信息
【问题讨论】:
-
您可以使用推送仪表板dashboard.pusher.com > 频道 > 调试控制台。刷新您的页面,您应该开始看到其中出现的内容。您很可能会看到类似“连接”>“已订阅”>“已占用”的内容。
-
对不起,需要说明这是自托管的 websocket
-
在这种情况下,您可能需要更改您的
nuxt.config.js,因为它具有推送器配置。 -
我基于github.com/qirolab/Laravel-WebSockets-Chat-Example 构建了这个。不同之处在于我使用的是 Laravel Passport 和 Nuxt.js。自托管推送器的选项在这里github.com/qirolab/Laravel-WebSockets-Chat-Example/blob/master/…
-
无法详细说明 laravel-websockets 的工作原理,但据我所知,它使用 pusher-js 的方式与使用 pusher.com 的方式相同,但只有你自己会使用包提供的websocket
标签: laravel websocket nuxt.js laravel-passport laravel-echo