laravel 5.5 跨域问题
在laravel的中间件(app/Http/Middleware)中添加新文件
可以用命令创建中间件
php artisan make:middleware 名字
并在新创建的文件中修改 handle 方法为:
public function handle($request, Closure $next) { $response = $next($request); $response->header('Access-Control-Allow-Origin', '*'); $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, multipart/form-data, application/json'); $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS'); $response->header('Access-Control-Allow-Credentials', 'false'); return $response; }
且在 app/Http/Kernel.php中 的 $middleware 中添加
AppHttpMiddleware名字::class,
跨域才解决成功。
有一个很大的坑:就是laravel在跨域访问时,用 dd() 打印会直接报错,前端控制台报错为
Failed to load url: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'url' is therefore not allowed access. The response had HTTP status code 500.