laravel 5.1 安装跨域插件,开启跨域API

composer https://packagist.org/packages/barryvdh/laravel-cors
请根据composer文档安装适合laravel版本的插件

laravel 5.1 版本安装

$ composer require barryvdh/laravel-cors 0.9.2

添加到config/app.php$providers数组

Barryvdh\Cors\ServiceProvider::class,

全局使用

开启全部路由的跨域,把 HandleCors类 添加 app/Http/Kernel.php 的 $middleware 属性中

protected $middleware = [
 // ...
 \Barryvdh\Cors\HandleCors::class,
];

组中间件

如果您想要在特定的中间件组或路由上允许CORS,请将HandleCors中间件添加到您的组中:

protected $middlewareGroups = [
 'web' => [
 // ...
 ],
 'api' => [
 // ...
 \Barryvdh\Cors\HandleCors::class,
 ],
];

添加配置文件

$ php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

注:当使用自定义header头,如:X-Auth-Token或者X-Requested-With,你必须设置allowedHeaders包含这些头。您也可以将其设置array('*')为允许所有自定义header
注意:如果您明确列入白名单,则必须包含Origin或请求将无法识别为CORS。

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,
]

也可以引用env文件配置

return [
    /*
     |--------------------------------------------------------------------------
     | Laravel CORS
     |--------------------------------------------------------------------------
     |
     | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
     | to accept any value.
     |
     */
    'supportsCredentials' => false,
    'allowedOrigins' => explode(',', env('HTTP_ORIGIN', '*')),
    'allowedHeaders' => explode(',', env('HTTP_HEADERS', 'Origin,Content-Type,Cookie,Accept,SJ-Auth-Token')),
    'allowedMethods' => explode(',', env('HTTP_METHODS', '*')),
    'exposedHeaders' => [],
    'maxAge' => 0,
];

《laravel 5.1 安装跨域插件,开启跨域API》上有2条评论

发表评论