使用 laravel-cors 實現 Laravel 的跨域配置
一、需求
一個項目需要進行前端跨域,不適用 jsonp
。
因此需要進行 cors 的設置。
最開始的時候,我使用的是路由中間件的方式,但是發現中間件不起作用。
// 路由中間件 public function handle($request, Closure $next) { $response = $next($request); $response->header('Access-Control-Allow-Origin', '*'); $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept'); $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS'); $response->header('Access-Control-Allow-Credentials', 'false'); return $response; }
因此后面直接使用了 laravel-cors
的庫來實現。
laravel-cors 庫 地址:
二、使用
安裝:
composer require barryvdh/laravel-cors
我使用的是 laravel 5.6 如果低於 5.5 版本需要手動進行注冊服務:
位於:config/app.php
,添加下面代碼
Barryvdh\Cors\ServiceProvider::class,
全局使用:
如果作為全局使用的中間件,則直接加入到 middleware 中即可:
修改 app/Http/kernel.php
文件:
protected $middleware = [ // ... \Barryvdh\Cors\HandleCors::class, ];
中間件組使用
如果只是在中間件組中使用,則加入相應的中間件組就OK
protected $middlewareGroups = [ 'web' => [ // ... ], 'api' => [ // ... \Barryvdh\Cors\HandleCors::class, ], ];
配置選項
導出配置:
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
配置的基本內容:
return [ /* |-------------------------------------------------------------------------- | Laravel CORS |-------------------------------------------------------------------------- | | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*') | to accept any value. | */ 'supportsCredentials' => false, 'allowedOrigins' => ['*'], 'allowedHeaders' => ['Content-Type', 'X-Requested-With'], 'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE'] 'exposedHeaders' => [], 'maxAge' => 0, ]
本文鏈接:http://www.ptbird.cn/laravel-cors-to-cors-laravel-app.html