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

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


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.


Laravel restricts the cross origin request due to security issues by default.We need to create a Cors middleware to the accept the request from different origin.

Step 1 : Create Cors middleware.

php artisan make:middleware Cors

Step 2 : Add below lines in handle function before return.

//header('Access-Control-Allow-Origin:  *');header('Access-Control-Allow-Origin:  http://localhost:4200');header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Authorization, Origin');header('Access-Control-Allow-Methods:  POST, PUT');

Step 3 : Register the middileware in app/Http/Kernel.php file.

Add below line in $middleware array \App\Http\Middleware\Cors::class,

Step 4 : Now we have to call the middleware in app/Http/Kernel.php file

Add below line in $routeMiddleware array 'cors' => \App\Http\Middleware\Cors::class,


https://github.com/barryvdh/laravel-cors

The laravel-cors package allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration.

Features

Handles CORS pre-flight OPTIONS requestsAdds CORS headers to your responses