首先在app/Http/Middleware文件夹内添加一个CORS.php文件 使用命令
php artisan make:middleware CORS
修改php文件内容 内容如下
<?php namespace App\Http\Middleware; use Closure; class CORS { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { return $next($request)->header('Access-Control-Allow-Origin','*') ->header('Access-Control-Allow-Methods','POST, GET, OPTIONS, PUT, DELETE') ->header('Access-Control-Allow-Headers','Content-Type, Accept, Authorization, X-Requested-With'); }}
然后根据官方文档 修改app/Http/Kernel.php文件,将CORS中间件注册到全局中间件即可。