Laravel Echo server responds nothing in browser

M a m a D :

I am following the tutorial given in https://medium.com/@dennissmink/laravel-echo-server-how-to-24d5778ece8b .

I installed laravel-echo-server, redis, socket.io, laravel-echo.

This is the configuration of laravel-echo-server init

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

This js code is at the bottom of app.blade.php which is included in all pages

<script type="module">
    import Echo from 'laravel-echo'

    window.io = require('socket.io-client');window.Echo = new Echo({
        broadcaster: 'socket.io',
        host: window.location.hostname + ':6001'
    });

    window.Echo.channel('test-event')
        .listen('ExampleEvent', (e) => {
            console.log(e);
        });
</script>

I created an event php artisan make:event ExampleEvent as follows

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;

class ExampleEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('test-event');
    }

    public function broadcastWith()
    {
        return [
            'data' => 'Hi bro!'
        ];
    }
}

and the following route

Route::get('test-broadcast', function(){
    broadcast(new \App\Events\ExampleEvent);
});

I also started a queue listener

php artisan queue:listen --tries=1

When I visit the page test-broadcast I see this in terminal

enter image description here

But the console of the browser shows nothing while the console.log(e); must return something. I also did this

    window.Echo.channel('test-event')
        .listen('ExampleEvent', (e) => {
            alert('hi')
            console.log(e);
        });

but nothing was alerted. It seems something is wrong with listening.

Thanks in advance.

update

I receive this error from console of browser when visiting login or any page includes app.blade.php

enter image description here

Update

I updated the script codes as below

    <script src="http://{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
    <script src="{{ asset('/js/app.js') }}"></script>
    <script type="module">
        import Echo from 'laravel-echo'

        window.Echo = new Echo({
         broadcaster: 'socket.io',
         host: window.location.hostname + ':6001'
         });

        window.Echo.channel('test-event')
            .listen('.ExampleEvent', (e) => {
                console.log(e);
            });
    </script>

The console still report error

TypeError: Error resolving module specifier: laravel-echo

update

I run

npm run development -- --watch

and this is the result

cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js "--watch"

'cross-env' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/
setup/webpack.config.js "--watch"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Mamad\AppData\Roaming\npm-cache\_logs\2020-03-05T14_59_30_604Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ watch: `npm run development -- --watch`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ watch script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Mamad\AppData\Roaming\npm-cache\_logs\2020-03-05T14_59_30_697Z-debug.log
Daniel Protopopov :

Altogether this what is required:

  1. Default Laravel installation
  2. composer require predis/predis
  3. Installation of NPM modules (laravel-echo-server, socket.io & laravel-echo)
  4. Set up Laravel Echo Server through console (mostly default settings, except for domain name): { "authHost": "http://echo", "authEndpoint": "/broadcasting/auth", "clients": [ { "appId": "fc3de97a1787ea04", "key": "ecf31edced85073f7dd77de1588db13b" } ], "database": "sqlite", "databaseConfig": { "redis": {}, "sqlite": { "databasePath": "/database/laravel-echo-server.sqlite" } }, "devMode": true, "host": null, "port": "6001", "protocol": "http", "socketio": {}, "secureOptions": 67108864, "sslCertPath": "", "sslKeyPath": "", "sslCertChainPath": "", "sslPassphrase": "", "subscribers": { "http": true, "redis": true }, "apiOriginAllow": { "allowCors": true, "allowOrigin": "http://echo:80", "allowMethods": "GET, POST", "allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id" } }

  5. Setup of Redis Server and connecting to it with Laravel broadcasting.php file

'default' => env('BROADCAST_DRIVER', 'redis')

or BROADCAST_DRIVER=redis in .env file

  1. Adding route in web.php

Route::get('/test-broadcast', function(){ broadcast(new \App\Events\ExampleEvent); return response('OK'); });

  1. Adding code in bootstrap.js:

import Echo from 'laravel-echo'

window.io = require('socket.io-client');
window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' });

ADDED

window.Echo.channel('MyChannel') .listen('.ExampleEvent', (e) => { console.log(e); });

  1. Running npm run dev to compile all Javascript modules
  2. Running laravel-echo-server start to start Laravel Echo Server
  3. Running php artisan queue:listen --tries=1 to start the listen queue
  4. Accessing the http://echo/test-broadcast

UPDATED

11.1 Adjust methods for the ExampleEvent to:

public function broadcastOn() { return new Channel('MyChannel'); }

public function broadcastAs() { return 'ExampleEvent'; }

11.2 In welcome.blade.php, before BODY tag, add

<script type="text/javascript" src="/js/app.js"></script>

11.3 in database.php, set redix prefix to empty string value

'prefix' => env('REDIS_PREFIX', '')

DO NOT FORGET TO RE-RUN npm run dev and clear browser cache

Results

Queue running

Laravel Echo Server console results

Client & Server alongside

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=26154&siteId=1