我正在尝试使用Laravel Echo连接到状态wesocket频道。我也在使用Laravel Passport。我遵循了很多教程,但得到的错误代码为403,错误代码为302,等等。我正在使用laravel-websockets库在本地托管Websocket服务器,以处理连接。 Vue是我的前端库。
这是我尝试过的:
编辑 BroadcastServiceProvider 的启动功能。
public function boot() {
Broadcast::routes(["prefix" => "api", "middleware" => "auth:api"]);
require base_path('routes/channels.php');
}
将授权令牌添加到Echo标头中,并在 bootstrap.js
中添加一个authEndpoint
属性
window.Echo = new Echo({
broadcaster: 'pusher',
authEndpoint: '/broadcasting/auth',
key: process.env.MIX_PUSHER_APP_KEY,
auth:{
headers:{
'Authorization': 'Bearer ' + auth_token,
}
},
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//encrypted: false
wsHost: window.location.hostname,
wsPort: 6001});
尝试从Vue 加入频道。
mounted(){
Echo.join(`game.0`)
.here((users) => {
alert("In the channel!");
})
.joining((user) => {
console.log("Someone entered");
})
.leaving((user) => {
console.log(user.name);
})
.listen('GameEvent', (e) => {
console.log("Hey")
});}
routes / channels.php 文件:
Route::prefix('/user')->group(function(){
Route::post('/login','api\v1\LoginController@Login');
Route::middleware('auth:api')->get('/all','api\v1\user\UserController@index');});
事件文件:
class GameEvent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $gameEvent;
public $gameId;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($gameEvent,$gameId)
{
//
$this->gameEvent = $gameEvent;
$this->gameId = $gameId;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
//return new PrivateChannel('channel-name');
return new PresenceChannel('game.0');
}
public function broadcastWith(){
return $this->gameEvent;
}
}
这时,如果我尝试连接到频道,则 broadcasting / auth 请求将获得302代码(找到)。我在另一篇文章中找到了答案,该文章声称可以通过将其添加到 routes / web.php 文件中来解决此问题。
Route::post('/broadcasting/auth', function(Request $request){
$pusher = new Pusher\Pusher(
env('PUSHER_APP_KEY'),
env('PUSHER_APP_SECRET'),
env('PUSHER_APP_ID'),
array(
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => false,
'host' => '127.0.0.1',
'port' => 6001,
'scheme' => 'http',
)
);
已解决,广播/身份验证请求给出了200个代码,我得到了以下响应:
{"auth":"ABCFEDG:0bfff7db6506158755b012a47873799849d4e6b331f68da4bedd1caea04ad657"}
但是here, joining, leaving
功能没有触发。
Echo.join('game.0')
.here((users) => {
alert("In the channel!");
})
我应该怎么做才能使它正常工作?
答案 0 :(得分:0)
您是否在channel.php中添加了身份验证路由? 请检查一下 您应该根据频道名称进行制作
Route::channel('game.'.$id,function($user,$id){
return .....
})