Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement laravel-echo client into Vue project

I'm developing an application with Vuetify (Vue.js) as front-end that communicates with api to laravel backend server.

I'm trying to make a system of notifications with laravel-echo-server working with socket.io. And using laravel-echo into client too.

The code that I uses into a component of client to test if connection works is:

// 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!')
})

This is the code of 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": ""
    }
}

I tried to modify apiOriginsAllow without success. The event is dispatched, I can see it into laravel-echo-server logs:

Channel: Prova
Event: App\Events\Prova

But after that, when I access into a component of the client that contains the connection code I can see in laravel-echo-server logs long error trace and the next error:

The client cannot be authenticated, got HTTP status 419

As you can see, I specified csrf token and authorization token into the headers of laravel echo client. But it doesn't work.

This is the code of routes/channels.php:

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

I only want to listen an event, it doesn't important if it is private or public because when it works, I want to put it into service worker. Then, I suppose that is better if it is public.

  • How can I use laravel echo client out of laravel project?
  • Will be a problem if I make private event and try to listen it into a service worker?
like image 727
axsor Avatar asked Oct 16 '22 19:10

axsor


2 Answers

Hello i am giving you the whole step how to configure VUE with Laravel and Echo functionality

Step1 Install laravel first

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

STEP 2 Set Variables change Broadcastserviceprovider

we first need to register the App\Providers\BroadcastServiceProvider. Open config/app.php and uncomment the following line in the providers array.

// App\Providers\BroadcastServiceProvider

We need to tell Laravel that we are using the Pusher driver in the .env file:

BROADCAST_DRIVER=pusher

add pusher Class in config/app.php

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

STEP 3 Add A Pusher to your laravel project

composer require pusher/pusher-php-server

STEP 4 Add following to config/broadcasting.php

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

STEP 5 Set Pusher Variable

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

STEP 6 Install Node

npm install

STEP 7 Installl Pusher js

npm install --save laravel-echo pusher-js 

STEP 8 uncommnet Following

// resources/assets/js/bootstrap.js

import Echo from "laravel-echo"

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

STEP 9 Before you create Migration

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

public function boot()
{
  Schema::defaultStringLength(191);
}
like image 183
jay dave Avatar answered Oct 21 '22 00:10

jay dave


To start client listeners i used Vuex. Then, when my application starts I dispatch the action INIT_CHANNEL_LISTENERS to start listeners.

index.js of channels MODULE vuex

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
}

actions.js of channels MODULE vuex

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 function in helpers That function dispatches notification on the browser

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

Then the backend uses laravel-echo-server like the question. Using redis to queue events and supervisor to start laravel-echo-server at startup of the server.

like image 23
axsor Avatar answered Oct 21 '22 00:10

axsor