Last active
November 12, 2020 14:25
-
-
Save Stiropor/fb2c556c653cdeb7565765e186d892fe to your computer and use it in GitHub Desktop.
Laravel CORS middleware that fuckin' worked!
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 | |
# By @andregarcia013 from https://github.com/fruitcake/laravel-cors/issues/471#issuecomment-651505665 | |
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) | |
{ | |
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, Authorization', | |
]; | |
if ($request->getMethod() == "OPTIONS"){ | |
//The client-side application can set only headers allowed in Access-Control-Allow-Headers | |
return response()->json('OK',200,$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