Laravel 配置 cors 记录

配置过程

Package 地址:https://github.com/barryvdh/laravel-cors

  • 安装

composer require barryvdh/laravel-cors

  • 配置中间件
1
2
3
4
5
6
7
8
9
10
11
// \App\Http\Kernel $routeMiddleware 中添加
protected $routeMiddleware = [
// ...
'cors' => \Barryvdh\Cors\HandleCors::class,
];

// $middlewareGroups => api => 中添加
'api' => [
// ...
'cors',
],
  • 发布配置文件至 config 目录

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

  • 禁用 API 的 CSRF 保护(可选)
1
2
3
4
// App\Http\Middleware\VerifyCsrfToken
protected $except = [
'api/*'
];