如何将laravel-echo客户端实现到Vue项目中

问题描述 投票:1回答:3

我正在开发一个Vuetify(Vue.js)作为前端的应用程序,它与api与laravel后端服务器进行通信。

我正在尝试使用laravel-echo-server和socket.io一起建立一个通知系统。并将laravel-echo用于客户端。

我用于客户端组件以测试连接是否有效的代码是:

// Needed by laravel-echo
window.io = require('socket.io-client')

let token = this.$store.getters.token

let echo = new Echo({
  broadcaster: 'socket.io',
  host: 'http://localhost:6001',
  auth: {
    headers: {
      authorization: 'Bearer ' + token,
      'X-CSRF-TOKEN': 'too_long_csrf_token_hardcoded'
    }
  }
})

echo.private('Prova').listen('Prova', () => {
  console.log('IT WORKS!')
})

这是laravel-echo-server.json的代码

{
    "authHost": "http://gac-backend.test",
    "authEndpoint": "/broadcasting/auth",
    "clients": [],
    "database": "redis",
    "databaseConfig": {
        "redis": {},
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": null,
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "sslCertPath": "",
    "sslKeyPath": "",
    "sslCertChainPath": "",
    "sslPassphrase": "",
    "apiOriginAllow": {
        "allowCors": false,
        "allowOrigin": "",
        "allowMethods": "",
        "allowHeaders": ""
    }
}

我试图修改apiOriginsAllow但没有成功。事件已分派,我可以在laravel-echo-server日志中看到它:

Channel: Prova
Event: App\Events\Prova

但在那之后,当我访问包含连接代码的客户端组件时,我可以在laravel-echo-server日志中看到长错误跟踪和下一个错误:

The client cannot be authenticated, got HTTP status 419

如您所见,我将csrf令牌和授权令牌指定到laravel echo client的头文件中。但它不起作用。

这是routes/channels.php的代码:

Broadcast::channel('Prova', function ($user) {
    return true;
});

我只想听一个事件,如果它是私有的或公共的并不重要,因为当它工作时,我想把它放到服务工作者。然后,我想如果它是公开的那就更好。

  • 如何在laravel项目中使用laravel echo客户端?
  • 如果我制作私人活动并试图将其收听服务工作者,那将会是一个问题吗?
php laravel events vue.js broadcast
3个回答
1
投票

您好,我将为您提供如何使用Laravel和Echo功能配置VUE的整个步骤

Step1首先安装laravel

composer create-project laravel/laravel your-project-name 5.4.*

步骤2设置变量更改Broadcastserviceprovider

我们首先需要注册App\Providers\BroadcastServiceProvider。打开config/app.php并取消注释providers数组中的以下行。

// App\Providers\BroadcastServiceProvider

我们需要告诉Laravel我们在.env文件中使用Pusher驱动程序:

BROADCAST_DRIVER=pusher

在config / app.php中添加pusher类

'Pusher' => Pusher\Pusher::class,

步骤3在您的laravel项目中添加Pusher

composer require pusher/pusher-php-server

步骤4在config / broadcasting.php中添加以下内容

'options' => [
          'cluster' => env('PUSHER_CLUSTER'),
          'encrypted' => true,
      ],

步骤5设置推杆变量

PUSHER_APP_ID=xxxxxx
PUSHER_APP_KEY=xxxxxxxxxxxxxxxxxxxx
PUSHER_APP_SECRET=xxxxxxxxxxxxxxxxxxxx
PUSHER_CLUSTER=xx

步骤6安装节点

npm install

STEP 7安装Pusher js

npm install --save laravel-echo pusher-js 

STEP 8 uncommnet以下

// resources/assets/js/bootstrap.js

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'xxxxxxxxxxxxxxxxxxxx',
    cluster: 'eu',
    encrypted: true
});

步骤9创建迁移之前

// app/Providers/AppServiceProvider.php
// remember to use
Illuminate\Support\Facades\Schema;

public function boot()
{
  Schema::defaultStringLength(191);
}

0
投票

对于套接字io

npm install socket.io --save

如果你得到无效的fram标头,请在bootstrap.js中设置auth终点,如下所示

window.Echo = new Echo({ authEndpoint : 'http://project/broadcasting/auth', broadcaster: 'pusher', key: '63882dbaf334b78ff949', cluster: 'ap2', encrypted: true });


0
投票

为了启动客户端监听器,我使用了Vuex。然后,当我的应用程序启动时,我发送动作INIT_CHANNEL_LISTENERS来启动监听器。

通道MODULE vuex的index.js

import actions from './actions'
import Echo from 'laravel-echo'
import getters from './getters'
import mutations from './mutations'

window.io = require('socket.io-client')

export default {
  state: {
    channel_listening: false,
    echo: new Echo({
      broadcaster: 'socket.io',
      // host: 'http://localhost:6001'
      host: process.env.CHANNEL_URL
    }),
    notifiable_public_channels: [
      {
        channel: 'Notificacio',
        event: 'Notificacio'
      },
      {
        channel: 'EstatRepetidor',
        event: 'BroadcastEstatRepetidor'
      }
    ]
  },
  actions,
  getters,
  mutations
}

通道MODULE vuex的actions.js

import * as actions from '../action-types'
import { notifyMe } from '../../helpers'
// import { notifyMe } from '../../helpers'

export default {
  /*
  * S'entent com a notifiable un event que té "títol" i "message" (Per introduir-los a la notificació)
  * */
  /**
   * Inicialitza tots els listeners per als canals. Creat de forma que es pugui ampliar.
   * En cas de voler afegir més canals "Notifiables" s'ha de afegir un registre al state del index.js d'aquest modul.
   * @param context
   */
  [ actions.INIT_CHANNEL_LISTENERS ] (context) {
    console.log('Initializing channel listeners...')
    context.commit('SET_CHANNEL_LISTENING', true)

    context.getters.notifiable_public_channels.forEach(listener => {
      context.dispatch(actions.INIT_PUBLIC_NOTIFIABLE_CHANNEL_LISTENER, listener)
    })
    // }
  },

  /**
   * Inicialitza un event notificable a través d'un canal.
   * Per anar bé hauria de tenir un titol i un missatge.
   * @param context
   * @param listener
   */
  [ actions.INIT_PUBLIC_NOTIFIABLE_CHANNEL_LISTENER ] (context, listener) {
    context.getters.echo.channel(listener.channel).listen(listener.event, payload => {
      notifyMe(payload.message, payload.title)
    })
  }
}

helper中的notifyMe函数该函数在浏览器上调度通知

export function notifyMe (message, titol = 'TITLE', icon = icon) {
  if (!('Notification' in window)) {
    console.error('This browser does not support desktop notification')
  } else if (Notification.permission === 'granted') {
    let notification = new Notification(titol, {
      icon: icon,
      body: message,
      vibrate: [100, 50, 100],
      data: {
        dateOfArrival: Date.now(),
        primaryKey: 1
      }
    })
  }

然后后端像问题一样使用laravel-echo-server。使用redis对事件进行排队,并在服务器启动时启动laravel-echo-server。

© www.soinside.com 2019 - 2024. All rights reserved.