Response to preflightLaravel – request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’

Last Updated: April 23, 2020

You will get following errors when you test your REST API application with React, Vue.JS and angular

You will get following errors when you call the REST api

 button_click2: function(){
            this.$http.post('http://yourdomain.com/api/somemethod', { name: "John", time: "2pm" })
            .then(function(response) {
               alert( "Data Loaded: " + response );
                console.log(response);
            // success
            }, function(response) {
            alert( "Data Loaded: " + response );
            console.log(response);
            });

         }

Failed to load http://yourdomain.com/api/somemethod 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:3333’ is therefore not allowed access.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://yourdomain.com/api/somemethod. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

To solve this issue in Laravel you can create middleware

php artisan make:middleware CORSMiddleware

Now you can add following code to App\Http\Middleware\CORSMiddleware

getMethod() === "OPTIONSS") {
            return response('')
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin');
            
        }

        return $next($request);
    }
}

In your App\Http\Kernel.php you can add the following code

 protected $middlewareGroups = [
        'web' => [
            .......
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
            \App\Http\Middleware\CORSMiddleware::class,
        ],
    ];

Now you can call the REST API from your javascript code without any issue

This also work well in Laravel