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'); }); });