• laravel 5.5 跨域问题 并且laravel的跨域 Access-Control-Allow-Origin 报错的坑


    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.
  • 相关阅读:
    第三周学习笔记
    质量属性
    第四周学习
    逻辑回归
    架构的概念
    第二周总结
    线性回归
    十步走-阅读笔记六
    十步走-阅读笔记五
    P2633 Count on a tree
  • 原文地址:https://www.cnblogs.com/wmmznb/p/9681222.html
Copyright © 2020-2023  润新知