【问题标题】:No 'Access-Control-Allow-Origin' header - Laravel没有“Access-Control-Allow-Origin”标头 - Laravel
【发布时间】:2017-09-19 19:46:21
【问题描述】:

XMLHttpRequest 无法加载 http://myapi/api/rating。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:8104' 不允许访问。响应的 HTTP 状态代码为 403。

我不知道为什么我不能发出 CORS 请求。我已经在这里安装了中间件,将它添加到全局http内核中,但它仍然不起作用。尝试根据 stackoverflow 建议创建自定义中间件,但这也不起作用。还尝试添加路由组。最后,我尝试在请求操作中手动设置响应标头。我真的被困住了 - 感谢您的帮助!

查看代码:https://gist.github.com/KerryRitter/0d7ababb7b9eb8d54f0ae55add9704a1

【问题讨论】:

  • 简单点,使用这个插件:github.com/barryvdh/laravel-cors
  • 我做了,就是我提到的中间件(忘了说了)。如我的要点所示,我添加到内核中
  • 如何保留它像:'middleware' => [\Barryvdh\Cors\HandleCors::class]
  • 好的,我删除了 'cors' 注册和 Cors 类。删除了路由组。删除了请求操作标头。我所拥有的只是受内核保护的 $middleware = [ ... \Barryvdh\Cors\HandleCors::class ];仍然没有运气:(
  • 解决了我的问题:我没有将“Barryvdh\Cors\ServiceProvider::class”添加到 config/app.php 提供程序数组中。

标签: php laravel laravel-5 cors


【解决方案1】:

我最近在 laravel 5.4 中遇到了这个错误,我正在向我自己的网站发送 ajax post 请求,但仍然遇到同样的错误,由于两个原因,我遇到了这个错误,

error: XMLHttpRequest cannot load https://[mydomain].com/quote/short. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[mydomain].com' is therefore not allowed access.

上述错误的原因是,我是从 https 域向 http 域发布请求,所以当我将其更改为 https 时,错误已解决,然后由于类似原因再次出现相同的错误,这是原因,这一次,域有www. 而请求的域没有,在我将www. 添加到两者之后,它就像一个魅力。

对于跨源请求,我习惯了以下解决方案:

  1. 创建一个中间件(在我的例子中是cors),代码如下

    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    
  2. 将中间件插入到kernal.php中的routeMiddleware数组中

    'cors' => \App\Http\Middleware\Cors::class,

  3. 将中间件添加到受尊重的路由

    Route::get('myRoute', ['middleware' => 'cors' , 'uses'=> 'MyController@Action']

希望这个答案能帮助遇到和我一样问题的人。

【讨论】:

    【解决方案2】:

    https://github.com/barryvdh/laravel-cors

    laravel-cors 包允许您使用 Laravel 中间件配置发送跨域资源共享标头。

    特点

    处理 CORS 飞行前 OPTIONS 请求 将 CORS 标头添加到您的响应中

    【讨论】:

    • 解决了我的问题:我没有将“Barryvdh\Cors\ServiceProvider::class”添加到 config/app.php 提供程序数组中。
    【解决方案3】:

    您可以在 kenel.php 中创建 Cors 中间件类并将其添加到应用程序的全局 HTTP 中间件堆栈中。此堆栈中的中间件将在对您的应用程序的每个请求期间运行。将中间件添加到该堆栈后,您不想在 api.php 文件中运行它。试试this 解决方案。

    【讨论】:

    • 可能值得引用您链接的帖子中的实际代码 sn-ps,以防它消失。
    • 很棒的故事,但这是一个编码网站,因此,在回答问题之前,您必须知道如何编码。
    【解决方案4】:

    如果您正在使用Laravel 5.5Laravel 5.x 并遇到类似No 'Access-Control-Allow-Origin' header is present on the requested resource 的问题。只需使用以下软件包并配置您的系统。

    第 1 步:

    composer require barryvdh/laravel-cors
    

    第 2 步

    您还需要将Cors\ServiceProvider 添加到您的config/app.php 提供程序数组中:

    FruitCake\Cors\CorsServiceProvider::class,
    

    要允许所有路由使用CORS,请在app/Http/Kernel.php 类的$middleware 属性中添加HandleCors 中间件:

    全球使用:

    protected $middleware = [
        // ...
        \Fruitcake\Cors\HandleCors::class,
    ];
    

    中间件用途:

    protected $middlewareGroups = [
       'web' => [
           // ...
       ],
    
       'api' => [
            // ...
            \Fruitcake\Cors\HandleCors::class,
        ],
    ];
    

    第 3 步

    安装完成后,运行以下命令以发布供应商文件。

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

    希望这个答案能帮助遇到和我一样问题的人。

    【讨论】:

    • 在 config/app.php 我们必须添加这个 Fruitcake\Cors\CorsServiceProvider::class,
    【解决方案5】:

    由于安全问题,Laravel 默认限制跨源请求。 我们需要创建一个 Cors 中间件来接受来自不同来源的请求。

    第 1 步:创建 Cors 中间件。

    php artisan make:middleware Cors
    

    第 2 步:在返回之前在句柄函数中添加以下行。

    //header('Access-Control-Allow-Origin:  *');
    header('Access-Control-Allow-Origin:  http://localhost:4200');
    header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Authorization, Origin');
    header('Access-Control-Allow-Methods:  POST, PUT');
    

    第三步:在 app/Http/Kernel.php 文件中注册中间件。

    Add below line in $middleware array 
    
    \App\Http\Middleware\Cors::class,
    

    第 4 步:现在我们要调用 app/Http/Kernel.php 文件中的中间件

    Add below line in $routeMiddleware array 
    
    'cors' => \App\Http\Middleware\Cors::class,
    

    【讨论】:

    • 谢谢,这是唯一对我有用的东西。我相信其他答案(或我在网上看到的东西)没有提到我们需要将中间件添加到 $middleware 数组的事实。
    • 非常感谢你没有使用任何包它完成了工作..
    • 使用* 工作而不是主机来源。错过了Cors.php middleware in the array as well 谢谢
    • 这是唯一的工作方法。网络上有很多错误的资源。
    【解决方案6】:

    您实际上需要的是为您的应用程序添加代理(前面)

    {
        "/api/*": {
          "target": "http://localhost:8000",
          "secure": false,
          "logLevel": "debug"
        }
      }
    

    在 package.json 中

    "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
    }, 
    ... 
    

    然后开始你的项目白色这个推荐

    npm start
    

    链接:https://www.youtube.com/watch?v=OjmZPPKaj6A

    【讨论】:

      【解决方案7】:

      好的,这是我的尝试。 如果我使用错误的令牌发布到受保护的 api,护照返回 401 并带有 {"message":"Unauthenticated."}

      但由于响应中不存在 cors 标头,我的 vue 应用出现 CORS 错误,无法处理响应代码。

      所以在 http/kernel.php $middlewarePriority 上的 laravel 5.8 在 \App\Http\Middleware\Authenticate::class 之前添加 \Barryvdh\Cors\HandleCors::class

      这是我的代码:

      protected $middlewareGroups = [
          'web' => [
              \App\Http\Middleware\EncryptCookies::class,
              \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
              \Illuminate\Session\Middleware\StartSession::class,
              // \Illuminate\Session\Middleware\AuthenticateSession::class,
              \Illuminate\View\Middleware\ShareErrorsFromSession::class,
              \App\Http\Middleware\VerifyCsrfToken::class,
              \Illuminate\Routing\Middleware\SubstituteBindings::class,
          ],
      
          'api' => [
              'throttle:300,1',
              'Localization',
              'bindings',
              'cors'
          ],
      ];
      
      protected $routeMiddleware = [
          'auth' => \App\Http\Middleware\Authenticate::class,
          'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
          'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
          'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
          'can' => \Illuminate\Auth\Middleware\Authorize::class,
          'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
          'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
          'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
          'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
      
          // Add Localization MiddleWare
          'Localization' => \App\Http\Middleware\localization::class,
          'cors' => \Barryvdh\Cors\HandleCors::class,
      ];
      
      protected $middlewarePriority = [
          \Illuminate\Session\Middleware\StartSession::class,
          \Illuminate\View\Middleware\ShareErrorsFromSession::class,
      
          //add to handle cors before authenticate
          \Barryvdh\Cors\HandleCors::class,
      
          \App\Http\Middleware\Authenticate::class,
          \Illuminate\Session\Middleware\AuthenticateSession::class,
          \Illuminate\Routing\Middleware\SubstituteBindings::class,
          \Illuminate\Auth\Middleware\Authorize::class,
      ];
      

      希望这对其他人有帮助

      【讨论】:

        【解决方案8】:

        对我来说,通过将 laravel 护照安装到我的 laravel 应用程序中解决了这个问题。

        【讨论】:

          【解决方案9】:

          我在一个复合项目前端 Reactjs 和 Laravel 后端工作时遇到 “预检请求未通过访问控制检查:没有 'Access-Control-Allow-Origin”。 我通过清除 Heroku 上部署的 Reactjs 应用程序的缓存解决了这个问题。

          How do I clear the build cache?

          【讨论】:

            【解决方案10】:

            简单的答案是将 Access-Control-Allow-Origin 标头设置为 localhost 或 *。这是我通常的做法: 创建一个名为Cors的简单中间件:

            php artisan make:middleware Cors
            

            将以下代码添加到app/Http/Middleware/Cors.php

            public function handle($request, Closure $next)
            {
                return $next($request)
                    ->header('Access-Control-Allow-Origin', '*')
                    ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
            }
            

            您可以将 * 替换为 localhost 或保持原样。

            下一步是加载middleware。将以下行添加到app/Http/Kernel.php 中的$routeMiddleware 数组中。

            'cors' => \App\Http\Middleware\Cors::class, 
            

            最后一步是在要设置访问源标头的路由上使用中间件。假设你说的是 laravel 5.3 中新的 api 路由,做的地方是app/Providers/RouteServiceProvider.php,在mapApiRoutes() 函数内部(你可以删除或注释函数之前的代码):

            Route::group([
                    'middleware' => ['api', 'cors'],
                    'namespace' => $this->namespace,
                    'prefix' => 'api',
                ], function ($router) {
                     //Add you routes here, for example:
                     Route::apiResource('/posts','PostController');
                });
            

            【讨论】:

              【解决方案11】:

              除了接受的答案中提到的步骤之外,我想添加一些我必须做的事情。

              即使在设置了这里提到的 HandleCors 之后,在几次生产部署(Nginx 上的 Laravel 版本 ^7.0)之后,我确实遇到了 CORS 错误。 在我运行 php artisan config:cachecomposer installcomposer dump-autoload 之后,它开始工作。

              希望这对尝试调试在部署期间未更新任何配置文件时出现的问题的人有所帮助。

              【讨论】:

                【解决方案12】:

                添加这个就可以了

                header('Access-Control-Allow-Origin:  *');
                header('Access-Control-Allow-Origin:  http://localhost:3000');
                header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Authorization, 
                Origin');
                header('Access-Control-Allow-Methods:  POST, PUT');
                

                【讨论】:

                • 您不能有多个 Access-Control-Allow-Origin 标头。
                • 您选择的标题和方法似乎是任意的,与问题无关。
                • 但这对我有用
                猜你喜欢
                • 2016-01-21
                • 1970-01-01
                • 1970-01-01
                • 2015-04-02
                • 2020-10-24
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多