Last active
May 6, 2023 18:15
-
-
Save saaiful/3ef381abcdb3d0de7b02f453243bb638 to your computer and use it in GitHub Desktop.
Enable CORS via Middleware in Laravel
This file contains 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
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Http\Response; | |
class CORS | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$origin = request()->headers->get('origin', '*'); | |
$headers = [ | |
'Access-Control-Allow-Methods' => 'GET, PUT, POST, DELETE, OPTIONS', | |
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization, apitoken, ApiToken', | |
'Access-Control-Allow-Origin' => $origin, | |
'Access-Control-Allow-Credentials' => 'true', | |
]; | |
if ($request->getMethod() == "OPTIONS") { | |
return response('', 200)->withHeaders($headers); | |
} | |
$response = $next($request); | |
foreach ($headers as $key => $value) { | |
$response->header($key, $value); | |
} | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
protected $routeMiddleware = []
add 'cors' => \App\Http\Middleware\CORS::class,