首页 > 解决方案 > 在 SPA 中授权广播频道

问题描述

我的项目分为两个应用程序:基于 vue 的客户端应用程序和基于 laravel 的服务器端 rest api 应用程序。我App\Providers\BroadcastServiceProvider::class,config/app.php文件中取消了注释。

默认广播授权路由是,/broadcasting/auth。由于它web应用了中间件,因此由于 CSRF 问题而显示 419。所以在BroadcastServiceProvider我改变了这个:

Broadcast::routes();

对此:

Broadcast::routes(['middleware' => ['auth:api']]);

但现在的问题是,每当我访问我的客户端应用程序时,我都会在控制台中收到以下错误:

GET http://localhost:8000/v1/login 405(不允许的方法)

我该如何解决?

我的客户端配置:

window.Echo = new Echo({
    authEndpoint: 'http://localhost:8000/broadcasting/auth',
    broadcaster: 'pusher',
    key: 'anyKey',
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true
});

window.Echo.private('test.1').listen('TestUpdated', (e) => {
    /*eslint-disable no-console*/
    console.log(e);
});

标签: phplaravelsingle-page-applicationlaravel-echo

解决方案


这就是我最终在api.php路由文件中所做的:

Route::post('/broadcast',function (Request $request){
    $pusher = new Pusher\Pusher(env('PUSHER_APP_KEY'),env('PUSHER_APP_SECRET'), env('PUSHER_APP_ID'));
    return $pusher->socket_auth($request->request->get('channel_name'),$request->request->get('socket_id'));
});

然后我authEndpoint在客户端应用程序中更改为该路由:

window.Echo = new Echo({
    authEndpoint: 'http://localhost:8000/broadcast',
    ...
}

推荐阅读