- 这个是Laravel 5.7的解决方案: https://learnku.com/articles/19246, 但是在5.8中可是可以用的, 不过需要设置:
-
$allow_origin = [ 'http://127.0.0.1:8080',//允许访问 ];
- 这个Github的解决方案也不适用5.8 : https://github.com/fruitcake/laravel-cors
- 比较好的解决方案如下 : https://www.oneue.com/articles/1336.html
第一步:创建中间件
-
php artisan make:middleware EnableCrossRequestMiddleware
第二步:编辑中间件
-
<?php namespace App\Http\Middleware; use Closure; class EnableCrossRequestMiddleware{ /** * @param $request * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { header('Content-Type: text/html;charset=utf-8'); header('Access-Control-Allow-Origin:*'); header('Access-Control-Allow-Methods:POST,GET,PUT,OPTIONS,DELETE'); // 允许请求的类型 header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies header('Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Origin,Access-token,Content-Length,Accept-Encoding,X-Requested-with, Origin,Access-Control-Allow-Methods'); // 设置允许自定义请求头的字段 return $next($request); } }
第三步:注册中间件(全局)
-
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ protected $middleware = [ //other \App\Http\Middleware\EnableCrossRequestMiddleware::class, ];
转载自: