Created
April 11, 2019 14:30
-
-
Save tomfordweb/7ba6e978ce8f5358acbe41e57647ed97 to your computer and use it in GitHub Desktop.
Laravel CORS Middlware: Allowing external CORS requests on your Laravel site.
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 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'=> 'GET', | |
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin' | |
]; | |
if($request->getMethod() == "OPTIONS") { | |
// The client-side application can set only headers allowed in Access-Control-Allow-Headers | |
return Response::make('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