composer require fruitcake/laravel-cors
發佈配置文件
php artisan vendor:publish --tag="cors"
自定義header
頭時,好比:Authorization
、Content-type
時,要設置allowed_headers
來包含這些header信息,也能夠設置爲[*]
以容許全部請求haeder信息若是要精確設置請求白名單,則必須將白名單包含進
allowed_methods
所對應的數組php
<?php return [ /* * You can enable CORS for 1 or multiple paths. * Example: ['api/*'] */ 'paths' => [], /* * Matches the request method. `[*]` allows all methods. */ 'allowed_methods' => ['*'], /* * Matches the request origin. `[*]` allows all origins. */ 'allowed_origins' => ['*'], /* * Matches the request origin with, similar to `Request::is()` */ 'allowed_origins_patterns' => [], /* * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers. */ 'allowed_headers' => ['*'], /* * Sets the Access-Control-Expose-Headers response header. */ 'exposed_headers' => false, /* * Sets the Access-Control-Max-Age response header. */ 'max_age' => false, /* * Sets the Access-Control-Allow-Credentials header. */ 'supports_credentials' => false, ];
allowed_origins
allowed_headers
和 allowed_methods
能夠設置成['*']
來容許全部值laravel
容許全部api跨域請求,添加HandleCors
中間件到app/Http/Kernel.php
的$middleware
屬性裏:
protected $middleware = [ // ... \Fruitcake\Cors\HandleCors::class, ];
在
$routeMiddleware
屬性裏添加:
protected $routeMiddleware = [ 'cors' => \Fruitcake\Cors\HandleCors::class, ]
在config/app.php
的providers
裏添加服務提供者:
'providers' => [ ... Fruitcake\Cors\CorsServiceProvider::class, ]
在routes/api.php
裏添加路由cors
中間件:
Route::middleware('cors')->group(function () { Route::get('dashboard', function () { return view('dashboard'); }); });