Cross-Origin Request Blocked error in Laravel 5.5

HTML 5 has introduced new standard Cross-origin resource sharing (CORS) which allows web applications to specify which origins (website or domains) are permitted to access resources on the server.

Fixing Cross-Origin Request (CORS) Blocked , Laravel access-control-allow-origin error in Laravel 5.5

When you are sending a request from Ajax, Angular js, React js, Vue js or any other javascript or front-end framework from one domain or website to other domain, website or server, you may face below errors like following
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . (Reason: CORS preflight channel did not succeed).

In this tutorial I am going to show you how to fix Cross-Origin Request Blocked, CORS preflight channel did not succeed, CORS preflight Access-Control-Allow-Origin , Access-Control-Allow-Methods , Access-Control-Allow-Headers errors in Laravel 5 ,Laravel 5.3, Laravel 5.4 or above.

Steps to fix or resolve Cross-Origin Request Blocked error in Laravel 5.5.

  • Step 1. Open command prompt or your terminal. Change your current working directory to your Laravel project directory.
    Example :

    cd var/www/html/laravel
  • Step 2.¬†install barryvdh/laravel-cors package. By running below command. It will take few minutes.composer require barryvdh/laravel-cors
  • Step 3. Once the installation process is completed run below command to publish the vendor files.
    php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
    

    Above command will create a file named cors.php in your config directory. Open that file make the changes as per your requirement.

    <?php
    
    return [
    
    /*
    |--------------------------------------------------------------------------
    | Laravel CORS
    |--------------------------------------------------------------------------
    |
    | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
    | to accept any value.
    |
    */
    
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],// ex: ['abc.com', 'api.abc.com']
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],// ex: ['GET', 'POST', 'PUT', 'DELETE']
    'exposedHeaders' => [],
    'maxAge' => 0,
    
    ];
    
  • Step 4.¬†Register the cors middleware in the application.Open app/Http/kernal.php and modify below code in your $routeMiddleware array
    protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'cors' => \Barryvdh\Cors\HandleCors::class, // add this line to enable cors to your routes
    ];
    

    For global usage modify below code

    protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \Barryvdh\Cors\HandleCors::class,
    ];
    
  • Step 5. Next using cor middleware in routes to allow cors.
    Note : Make sure you return a json as output;

    Route::post('/api/your_url', ['middleware' => 'cors',function(){
    
    	return ['status'=>'success'];
    }]);
    
    OR 
    
    Route::post('/api/your_url', function () {
       return ['status'=>'success'];
    })->middleware('cors');
    
    OR
    
    Route::group(['middleware' => 'cors'], function() {
       Route::post('/api/your_url', function () {
    	   return ['status'=>'success'];
    	});
    });
    
    Route::group(['middleware' => 'cors'], function() {
       Route::post('/api/your_url','YourController@function' );
    
    });
    
  • Step 6. Open app/Http/Middleware/VerifyCsrfToken.php and allow api/ url groups to by pass VerifyCsrfToken middleware.
    protected $except = [
    '/webpush','/webpush/*','api/*'
    ];
    

You have successfully configured and Cors on Laravel 5.5. If you face any problem, please comment below.
Also read: Top Laravel Interview questions

Thanks You !!

2 thoughts to “Cross-Origin Request Blocked error in Laravel 5.5”

  1. I still get problem…
    “`
    Failed to load https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=AIzaSyASQCfY2r2PxAwS24xhdC7pBuG23WYX6kU: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. Origin ‘https://dikbudtomohon.dev’ is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
    “`

    This is my JS

    geocode();
    function geocode() {
    axios.get(
    ‘https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=AIzaSyASQCfY2r2PxAwS24xhdC7pBuG23WYX6kU’,
    {
    headers: {‘X-Requested-With’: ‘XMLHttpRequest’},
    responseType: ‘json’,
    withCredentials: true,
    }
    ).then(function (response) {
    console.log(response);
    }).catch(function (error) {
    console.log(error)
    });
    }

Leave a Reply

Your email address will not be published. Required fields are marked *