0

Im trying to set up laravel websockets on localhost using this library

And I am getting this error enter image description here

I have installed the package and started the service on my localhost running php artisan websockets:serve

my Bootstrap.js is:

import Echo from "laravel-echo"

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
});
window.Echo.channel('DemoChannel').listen('WebsocketDemoEvent',(e) => function() {
    console.log(e);
});
MLEE
  • 17
  • 3
B L Praveen
  • 1,812
  • 4
  • 35
  • 60

1 Answers1

-1

create a new middleware: app/Http/Middleware/cors.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

add the cors middleware to app/Http/Kernel.php

protected $routeMiddleware = [
    //default laravel middleware
    'cors' => \App\Http\Middleware\Cors::class,
];

add the new cors middleware to your route

Route::get('/broadcast', function () {
    broadcast(new hello());
});
})-> middleware('cors'); 

---caution--- this will now accept requests from ANYWHERE.

this is fine on localhost but when you move to a live server you need to change:

->header('Access-Control-Allow-Origin', '*')

to

->header('Access-Control-Allow-Origin', 'http://www.yourdomain.com')

or you need to create an api key to pass along with each request so you can have the public api (not reccomended but is a viable workaround)

aidan byrne
  • 524
  • 1
  • 5
  • 11