如何在 Laravel 5.1 中启用 CORS
将 CORS(跨域资源共享)集成到 Laravel 中可以让服务器授予跨域权限原始 API 调用。本文将指导您完成在 Laravel 5.1 版本中启用 CORS 的具体方法。
Laravel 的 CORS 中间件
// app/Http/Middleware/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 文件:
// app/Http/Kernel.php protected $routeMiddleware = [ //other middlewares 'cors' => 'App\Http\Middleware\CORS', ];
在路由中应用 CORS
最后,在要允许交叉的路由中使用 cors 中间件原始 API 调用:
Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));
Laravel 注释^8.0
在 Laravel 8.0 及以上版本中,由于命名空间更改,请务必使用以下语法来注册 CORS 中间件:
// app/Http/Kernel.php protected $routeMiddleware = [ //other middlewares 'cors' => 'App\Http\Middleware\CORS', ]; // routes/web.php or routes/api.php use App\Http\Controllers\ExampleController; Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');
以上是如何在 Laravel 5.1 中启用 CORS?的详细内容。更多信息请关注PHP中文网其他相关文章!