我从 reactJS 获得 laravel 私人频道的 401(未授权)状态。
这适用于 userId=1 但为所有其他用户返回 401。
这是 Laravel 的代码
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes([
"middleware" => ['api', 'jwt.auth'],
"prefix" => "api"
]);
require base_path('routes/channels.php');
}
}
class AppointmentEvent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $appointment;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($appointment)
{
$this->appointment = $appointment;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('App.User.' . $this->appointment->patient_id);
}
}
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
这是反应代码
const token = JSON.parse(localStorage.getItem("patientToken"));
const options = {
broadcaster: 'pusher',
key: '1c**************61',
cluster: 'ap2',
encrypted: true,
authEndpoint: 'http://localhost/heal/api/broadcasting/auth',
auth: {
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json',
},
},
};
window.Echo = new Echo(options);
var p = localStorage.getItem("patientId");
window.Echo.private(`App.User.${p}`).listen('ConfirmAppointmentEvent', (e) => {
alert("Doctor accepted your appointment")
console.log(e)
});
完美适用于 user_id 1,但不适用于其他我取消注释的人App\Providers\BroadcastServiceProvider::class,
Laravel 版本 7.30.0