No Access-Control-Allow-Origin header is present on the requested resource - Laravel 5.5






How to solve No 'Access-Control-Allow-Origin' header is present on the requested resource with Laravel 5.5?

First you need to understand why this is happening, the reason is simple, you are sending an API request from another domain to your server and for security reason, it won't allow you to access the resources.

ie:
You are creating a mobile application using phonegap, wrote a javascript ajax call to your local Laravel application, when you click on the button that initiate the call, this error shows up:
Failed to load http://xxxxxxxxxx.local: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxxxxxxxx.local' is therefore not allowed access. The response had HTTP status code 500.


Follow the below steps to stop this from happening:


1)Use your command line and go to your Laravel installation, type the below command:


composer require barryvdh/laravel-cors

2)When installed make sure you have in your config/app.php this class:

Barryvdh\Cors\ServiceProvider::class,


3)If you want this to work globally in your app add this line to app/Http/Kernel.php

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

4)If you only want to use it on your API routes, use the below code in app/Http/Kernel.php

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

Hope this will be useful to all the Laravel readers!


Leave us a comment