Here is my CORS middleware:
<?php namespace AppHttpMiddleware;
use Closure;
class CORS {
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $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'=> 'POST, GET, OPTIONS, PUT, DELETE',
'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;
}
}
To use CORS middleware you have to register it first in your appHttpKernel.php file like this:
protected $routeMiddleware = [
//other middlewares
'cors' => 'AppHttpMiddlewareCORS',
];
Then you can use it in your routes
Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));
Edit: In Laravel ^8.0 you have to import the namespace of the controller and use the class like this:
use AppHttpControllersExampleController;
Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…