If you don’t have any idea what CORS is, then please skip this.
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; | |
use Illuminate\Http\Response; | |
class CORS | |
{ | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$origin = request()->headers->get('origin', '*'); | |
$headers = [ | |
'Access-Control-Allow-Methods' => 'GET, PUT, POST, DELETE, OPTIONS', | |
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization, apitoken, ApiToken', | |
'Access-Control-Allow-Origin' => $origin, | |
'Access-Control-Allow-Credentials' => 'true', | |
]; | |
if ($request->getMethod() == "OPTIONS") { | |
return response('', 200)->withHeaders($headers); | |
} | |
$response = $next($request); | |
foreach ($headers as $key => $value) { | |
$response->header($key, $value); | |
} | |
return $response; | |
} | |
} |
Save as CORS.php
in the Middleware
folder.
Edit app\Http\Kernel.php
and add your middleware in api / routeMiddleware.