这是我的CORS中间件:
<?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'=> '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;
}
}
要使用 CORS 中间件,您必须首先在 app\Http\Kernel.php 文件中注册它,如下所示:
protected $routeMiddleware = [
//other middlewares
'cors' => 'App\Http\Middleware\CORS',
];
然后,您可以在路线中使用它
Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));
编辑:在Laravel ^ 8.0中,您必须导入控制器的命名空间并使用如下类:
use App\Http\Controllers\ExampleController;
Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');