0

我正在使用 Laravel(背面)和 Vuejs(使用 Vuex)开发一个项目。我还使用 Sanctum:auth 对用户进行身份验证,使用 laravel-websockets 和 Laravel-Echo 进行广播。

之前,我在控制台上收到了一个身份验证问题,错误为:“POST 'broadcast / auth' 404 not found”。

在看了一个在同一个项目中结合 Sanctum、Vue 和 Laravel Echo 的教程后,我能够解决它。

但是,现在我测试了该服务,我意识到我可以收听公共频道但不能收听私人频道。

从我在 websockets-dashboard 上看到的内容来看,我什至没有订阅私人频道。

在我的存档 .vue 中:

import room from './Room'
import axios from 'axios'
import Echo from 'laravel-echo'
import Pusher from 'pusher-js'
console.log(Pusher);
...
export default {
...
   data: () => ({
        ...
        Echos:undefined
   }),
  
   mounted(){
    ...
    this.instantiatingEcho();
   },
   
   methods:{
   
   ...
   instantiatingEcho(){
   
        axios({
        method: "GET",
        url: "http://127.0.0.1:8000/api/users",
        headers: {
            Authorization: `Bearer ${this.$store.state.user.token}`,
        },
        })
        .then(({ data }) => {
            console.log(data);

            this.Echos = new Echo({
                broadcaster: 'pusher',
                key: process.env.VUE_APP_WEBSOCKETS_KEY,
                wsHost: process.env.VUE_APP_WEBSOCKETS_SERVER,
                wsPort: 6001,
                forceTLS: false,
                disableStats: true,
                authorizer: (channel, options) => {
                    console.log(options);
                    return {
                        authorize: (socketId, callback) => {
                            axios({
                                method: "POST",
                                url: "http://127.0.0.1:8000/api/broadcasting/auth",
                                headers: {
                                    Authorization: `Bearer ${this.$store.state.user.token}`,
                                },
                                data: {
                                    socket_id: socketId,
                                    channel_name: channel.name,
                                },
                            })
                            .then((response) => {
                                callback(false, response.data);
                            })
                            .catch((error) => {
                                callback(true, error);
                            })
                        },
                    }
                }
            })
        })

        this.enterinrom();
    },

    enterinrom(){
        this.Echos.private('Room.2')
        .listen('BroadcastRoom', (e) =>{
            console.log(e)
        });    
    },
    
    }
}

频道.php:

 Broadcast::channel('Room.{id}', function ($id){
     return true;
 });

事件:

 <?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Broadcasting\RoomChannel;

class BroadcastRoom implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $mensage;
    public $id;


    public function __construct($mensage, $id)
    {
       $this->mensage = $mensage;
       $this->id = $id;
    }

    public function broadcastWith()
    {
       return ["mensage" => $this->mensage];
    }


    public function broadcastOn()
    {
        return new PrivateChannel('Room.'.$this->id);
    }

}

api.php:

   ...

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

   Route::middleware('auth:sanctum')->get('/users', function (Request $request) {
       return $request->user();
   });

   Route::post('/users/login', function (Request $request) {

   $user = User::where('email', $request->email)->first();

   if (!$user || ($request->password != $user->password)) {
        return response([
            'message' => ['These credentials do not match our records.']
            ], 404);
   }

   $token = $user->createToken('idiot-online-token')->plainTextToken;

   $response = [
        'user' => $user,
        'token' => $token
   ];

   return response($response, 201);
});

网页.php:

Route::get('/enviaevento/{id}', function ($id) {
    return event(new \App\Events\BroadcastRoom('Uai só...', $id));
});

config/app.php 中的 App\Providers\BroadcastServiceProvider::class 未注释。

结果: 在此处输入图像描述

有人可以帮助我吗?

4

1 回答 1

0

在授权者属性中,请确保正确使用响应。您可以尝试使用响应而不是 response.data。我已经在这个问题上停留了一段时间,只是为了意识到文档中的片段不足以满足我的情况。

import room from './Room'
import axios from 'axios'
import Echo from 'laravel-echo'
import Pusher from 'pusher-js'
console.log(Pusher);
...
export default {
...
   data: () => ({
        ...
        Echos:undefined
   }),
  
   mounted(){
    ...
    this.instantiatingEcho();
   },
   
   methods:{
   
   ...
   instantiatingEcho(){
   
        axios({
        method: "GET",
        url: "http://127.0.0.1:8000/api/users",
        headers: {
            Authorization: `Bearer ${this.$store.state.user.token}`,
        },
        })
        .then(({ data }) => {
            console.log(data);

            this.Echos = new Echo({
                broadcaster: 'pusher',
                key: process.env.VUE_APP_WEBSOCKETS_KEY,
                wsHost: process.env.VUE_APP_WEBSOCKETS_SERVER,
                wsPort: 6001,
                forceTLS: false,
                disableStats: true,
                authorizer: (channel, options) => {
                    console.log(options);
                    return {
                        authorize: (socketId, callback) => {
                            axios({
                                method: "POST",
                                url: "http://127.0.0.1:8000/api/broadcasting/auth",
                                headers: {
                                    Authorization: `Bearer ${this.$store.state.user.token}`,
                                },
                                data: {
                                    socket_id: socketId,
                                    channel_name: channel.name,
                                },
                            })
                            .then((response) => {
                                callback(false, response);
                            })
                            .catch((error) => {
                                callback(true, error);
                            })
                        },
                    }
                }
            })
        })

        this.enterinrom();
    },

    enterinrom(){
        this.Echos.private('Room.2')
        .listen('BroadcastRoom', (e) =>{
            console.log(e)
        });    
    },
    
    }
}
于 2021-01-26T05:19:26.770 回答