【问题标题】:How to implement laravel-echo client into Vue project如何在 Vue 项目中实现 laravel-echo 客户端
【发布时间】:2018-10-05 15:05:19
【问题描述】:

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

我正在尝试使用 laravel-echo-serversocket.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

如您所见,我在 laravel echo 客户端的 headers 中指定了 csrf 令牌和授权令牌。但它不起作用。

这是routes/channels.php的代码:

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

我只想监听一个事件,它是私有的还是公共的并不重要,因为当它工作时,我想把它放到 service worker 中。那么,我想如果它是公开的会更好。

  • 如何在 laravel 项目中使用 laravel echo 客户端?
  • 如果我制作私人事件并尝试将其监听到服务人员中会有问题吗?

【问题讨论】:

  • 你已经解决了吗?我还想用 CORS 设置(Laravel 后端和 Vue 单页应用程序)实现 Echo。但是我的发展比你还差。我仍然不明白如何从事件中捕获返回的数据。如果我检查日志(laravel.log 文件),广播已通过有效负载成功发送,但在前端它也出现错误No 'Access-Control-Allow-Origin' header。我已经用不记名令牌设置了标头,但仍然出现错误
  • 更新,当我在 laravel 项目中设置 CORS 时,错误已经消失。现在,主要问题和你一样,如何在 laravel 项目之外使用 laravel echo 客户端:D
  • @MuhammadIzzuddinAlFikri 我写了答案stackoverflow.com/a/52256566/8950695
  • 419 是一个 CSRF 错误,使用没有将“_token”设置为 Laravel 的 CSRF 的 POST。您可以在中间件的 VerifyCSRFToken.php 中放置一个异常,或者更改您的身份验证策略并使用带有 Passport 或 JWT 的 API。

标签: php laravel events vue.js broadcast


【解决方案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,

第三步在你的 laravel 项目中添加一个 Pusher

composer require pusher/pusher-php-server

步骤 4 将以下内容添加到 config/broadcasting.php

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

第五步设置推送变量

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

步骤 6 安装节点

npm install

步骤 7 安装 Pusher js

npm install --save laravel-echo pusher-js 

第 8 步取消关注

// 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);
}

【讨论】:

  • 非常感谢您一步一步的回答。但是我使用,vue 进入了不同的项目和socket.io。目前我在 echo 实例上使用 channel 函数而不是 private 来解决它。 (我使用了private,因为频道是公开的,所以它不起作用)。
【解决方案2】:

为了启动客户端监听器,我使用了 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 的 action.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)
    })
  }
}

助手中的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 对事件进行排队,并使用 supervisor 在服务器启动时启动 laravel-echo-server。

【讨论】:

  • 我会和你的技术栈一样,后端使用 laravel-echo-server 用于 websocket,redis 用于队列事件。只有我不使用的主管。我尝试了您的解决方案,但我想我现在知道我的项目的罪魁祸首。我的问题是 vue 应用程序无法接收事件的有效负载。我想为什么它没有收到,因为在我的echo.connector.channels 上它仍然是空的,甚至已经调度了 vuex 操作。这有什么线索吗?
  • 对不起@MuhammadIzzuddinAlFikri,但我在实现它时遇到了很多困难。我希望对你有用,但我不能
  • 没问题老兄,我会解决我的问题 :) 感谢您的信息
  • @MuhammadIzzuddinAlFikri 我面临同样的问题,您能解释一下您是如何解决问题的吗?
  • 你在哪里指定令牌?
【解决方案3】:

对于socket io

npm install socket.io --save

如果你的帧头无效,请在 bootstrap.js 中设置身份验证端点,如下所示

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

【讨论】:

    猜你喜欢
    • 2019-12-20
    • 2021-07-02
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 2017-09-15
    • 2023-01-30
    • 2018-11-23
    • 1970-01-01
    相关资源
    最近更新 更多