Last active
August 15, 2020 20:23
-
-
Save pablorsk/5df7aad7a1c5f7612c6bc3d46505e23e to your computer and use it in GitHub Desktop.
CORS middleware for Lumen and PSR-7
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 | |
/* | |
some code on bootstrap/app.php... | |
*/ | |
$app->middleware([ | |
App\Http\Middleware\CorsMiddleware::class | |
/* maybe, antother middlewares... */ | |
]); | |
/* | |
some code... | |
*/ |
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 | |
namespace App\Http\Middleware; | |
use Closure; | |
class CorsMiddleware | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
//Intercepts OPTIONS requests | |
if($request->isMethod('OPTIONS')) { | |
$response = response('', 200); | |
} else { | |
// Pass the request to the next middleware | |
$response = $next($request); | |
} | |
// Adds headers to the response | |
$response->headers->set('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE'); | |
$response->headers->set('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers')); | |
$response->headers->set('Access-Control-Allow-Origin', '*'); | |
// Sends it | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment