Search code examples
phplaravellaravel-5cors

No 'Access-Control-Allow-Origin' header - Laravel


XMLHttpRequest cannot load http://myapi/api/rating. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8104' is therefore not allowed access. The response had HTTP status code 403.

I can't figure out why I can't make CORS requests. I've install the middleware here, added it to the global http kernel, but it still doesn't work. Tried to create a custom middleware given stackoverflow suggestions but that also did not work. Also tried adding a Route group. Lastly, I tried setting the response headers manually in the request action. I'm really stuck - help is appreciated!

See for code: https://gist.github.com/KerryRitter/0d7ababb7b9eb8d54f0ae55add9704a1


Solution

  • If you are using Laravel 5.5 & Laravel 5.x and facing same problem like No 'Access-Control-Allow-Origin' header is present on the requested resource. Just use following package and config your system.

    Step 1:

    composer require barryvdh/laravel-cors
    

    Step 2

    You also need to add Cors\ServiceProvider to your config/app.php providers array:

    FruitCake\Cors\CorsServiceProvider::class,
    

    To allow CORS for all your routes, add the HandleCors middleware in the $middleware property of app/Http/Kernel.php class:

    For global uses:

    protected $middleware = [
        // ...
        \Fruitcake\Cors\HandleCors::class,
    ];
    

    For middleware uses:

    protected $middlewareGroups = [
       'web' => [
           // ...
       ],
    
       'api' => [
            // ...
            \Fruitcake\Cors\HandleCors::class,
        ],
    ];
    

    Step 3

    Once your installation completed run below command to publish the vendor files.

    php artisan vendor:publish --provider="Fruitcake\Cors\ServiceProvider"
    

    Hope this answer helps someone facing the same problem as myself.