我正在尝试授权私人频道。
我使用 Vue.js 作为 SPA,使用 Laravel Sanctum 进行身份验证,使用 Laravel 作为 api。
作为 Laravel 的文档,我在 "routes" 文件夹下的 "channels.php" 上编写了我的频道回调。但它没有用。当我尝试对频道进行身份验证时,它说的是 403。然后我将我的频道回调代码移动到“api.php”并且它正在工作。
你能解释一下为什么吗?我想在“channel.php”上写我的频道回调。我正在使用 Laravel 8。这是我的简单代码。
这是在我的 MessageSent 事件中。
public function broadcastOn()
{
return new PrivateChannel("message");
}
public function broadcastAs()
{
return "message-sent";
}
这些是我移至 api.php 的代码,因为它们在 channels.php 中不起作用。
Broadcast::channel('message', function ($user) {
return true;
});
这是在 BroadcastServiceProvider 里面。据我所知,“channels.php”包含在 boot() 函数中,其中的代码应该可以工作。
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
这是我的 Laravel 回显代码。
window.Echo = new Echo({
broadcaster: "pusher",
cluster: "ap1",
encrypted: true,
key: "my_key",
authorizer: (channel) => {
return {
authorize: (socketId, callback) => {
api.post('broadcasting/auth', {
socket_id: socketId,
channel_name: channel.name
})
.then(response => {
callback(false, response.data);
})
.catch(error => {
callback(true, error);
});
}
};
}
});
window.Echo.private("message").on("message-sent", (data) => {
console.log(data);
})