Cross-Origin Request Blocked error in Laravel 5

2024-03-19 09:19:11 Mayank Laravel

Cors in Laravel

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 a 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.

This post is submitted by one of our members. You may submit a new post here.

Related Tricks