Created
July 13, 2017 00:36
-
-
Save ragingprodigy/72136d4fc2331a8f22da10ec99f97cf3 to your computer and use it in GitHub Desktop.
CORS Middleware File for Laravel/Lumen
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
<?php | |
declare(strict_types = 1); | |
/** | |
* @author Oladapo Omonayajo <[email protected]> | |
* Created on 3/27/2017, 18:21 | |
*/ | |
namespace App\Http\Middleware; | |
class CorsMiddleware | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, \Closure $next) | |
{ | |
$referrer = $_SERVER['HTTP_REFERER'] ?? ''; | |
$referrer = substr($referrer, 0, strlen($referrer) - 1); | |
$headers = [ | |
'Access-Control-Allow-Origin' => $referrer, | |
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE', | |
'Access-Control-Allow-Credentials' => 'true', | |
'Access-Control-Max-Age' => '86400', | |
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With' | |
]; | |
if ($request->isMethod('OPTIONS')) { | |
return response()->json(['method' => 'OPTIONS' ], 200, $headers); | |
} | |
$response = $next($request); | |
foreach ($headers as $key => $value) { | |
$response->headers->set($key, $value); | |
} | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment