Forked from jack2jm/Laravel - Allow Specific Routes for Cors (Cross Origin Allowed region))
Created
February 12, 2024 05:50
-
-
Save Bhavya8181/ac7a98c808fce55c8f9c8a856a3705e7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 1. Create a cors file | |
| Run this artisan command: | |
| php artisan make:middleware Cors | |
| 2. Now open Cors.php from *App\Http\Middleware* folder and replace handle() function with this code: | |
| public function handle($request, Closure $next) | |
| { | |
| //return $next($request); | |
| header("Access-Control-Allow-Origin: *"); | |
| // ALLOW OPTIONS METHOD | |
| $headers = [ | |
| 'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE', | |
| 'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin' | |
| ]; | |
| if($request->getMethod() == "OPTIONS") { | |
| // The client-side application can set only headers allowed in Access-Control-Allow-Headers | |
| return Response::make('OK', 200, $headers); | |
| } | |
| $response = $next($request); | |
| foreach($headers as $key => $value) | |
| $response->header($key, $value); | |
| return $response; | |
| } | |
| 3. Lastly, open Kernel.php from App\Http folder add the below line to the $routeMiddleware array: | |
| protected $routeMiddleware = [ | |
| //other routes | |
| 'opencors' => \App\Http\Middleware\Cors::class, | |
| ]; | |
| 4. Now add middleware to that route. use below line. | |
| Route::get('/eva-api/get-reports', ['middleware' => 'opencors', 'as' => 'getReport', 'uses' => 'Boilerplate\ChatbotsController@getChatbotsReportByParams']); | |
| Reference link - https://www.codegrepper.com/code-examples/whatever/has+been+blocked+by+CORS+policy%3A+Response+to+preflight+request+doesn%27t+pass+access+control+check%3A+It+does+not+have+HTTP+ok+status. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment