Skip to content

Instantly share code, notes, and snippets.

@ragingprodigy
Created July 13, 2017 00:36
Show Gist options
  • Save ragingprodigy/72136d4fc2331a8f22da10ec99f97cf3 to your computer and use it in GitHub Desktop.
Save ragingprodigy/72136d4fc2331a8f22da10ec99f97cf3 to your computer and use it in GitHub Desktop.
CORS Middleware File for Laravel/Lumen
<?php
declare(strict_types = 1);
/**
* @author Oladapo Omonayajo <oladapo.omonayajo@lazada.com.ph>
* 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