Cross-Origin Resource Sharing (CORS) is mechanism which allow browser to share the resources between the other domain or port. if the cors is disabled in api or server then other domain can’t access the apis and resource of server.
Example: if a server A wants to access the apis of server B then its impossible until cors is not enable on server B. you will get an error.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource Reason: CORS header ‘Access-Control-Allow-Origin’ missing
how to enable cors in php?
function cors() { // Allow from any origin if (isset($_SERVER['HTTP_ORIGIN'])) { // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one // you want to allow, and if so: header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 86400'); // cache for 1 day } // Access-Control headers are received during OPTIONS requests if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) // may also be using PUT, PATCH, HEAD etc header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); exit(0); } echo "You have CORS!"; }
you can call cors function in header file or in the file which is includes in all files of your project.
How to enable cors in laravel?
- Create a middleware using the artisan command or manually in Http/middleware folder
php artisan make:middleware Cors
or you can also create a file in Cors.php in Http/middleware folder and edit the file
<?php namespace App\Http\Middleware; use Closure; class Cors { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { return $next($request) ->header("Access-Control-Allow-Origin", "{$_SERVER['HTTP_ORIGIN']}") ->header('Access-Control-Allow-Credentials','true') ->header('Access-Control-Max-Age', '86400'); ; } }
2. Add the middleware to Http/Kernel.php in $routeMiddleware
protected $routeMiddleware = [ ...... 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'cors' => \App\Http\Middleware\Cors::class, //Cors added ];
So, you can use it in your routes with the cors
name:
Route::group(['namespace' => 'User', 'middleware' => ['cors'], 'prefix' => 'user'], function () { });
Laravel cors using the package:
you can also use the package to enable the cors in laravel
https://github.com/fruitcake/laravel-cors
Enable cors plugin in chrome or any browser
We can also disable the security of cors in browser using the chrome extension
hence, this will disable the cors in browser but it’s an temporary solution for cors.