【问题标题】:CORS problem with Laravel Api based on Clean-Laravel-Api project基于 Clean-Laravel-Api 项目的 Laravel Api 的 CORS 问题
【发布时间】:2021-11-17 13:09:02
【问题描述】:

我正在尝试基于gentritabazi01/Clean-Laravel-Api 和 Laravel8 的 larapi 制作和 api 服务。当我从不同的服务器向我的 api 发出请求时,我无法解决 CORS 的问题。相关内容如下:

CORS 策略已阻止从源“http://segu........com”访问“https://dev.......com/users”处的 XMLHttpRequest:响应预检请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

从 2 天前开始,我一直在阅读 CORS 和 Laravel 的文档,任何解决方案都可以解决我的问题。我尝试创建一个中间件并添加必要的标头:

//Infrastructure\Http\Middlewares\Cors
    <?php
    use Closure;
    class Cors
    {
      public function handle($request, Closure $next)
      {
        return $next($request)
           //Url a la que se le dará acceso en las peticiones
          ->header("Access-Control-Allow-Origin", "*")
          //Métodos que a los que se da acceso
          ->header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
          //Headers de la petición
          ->header("Access-Control-Allow-Headers", "*"); 
      }
    }

我尝试使用来自 laravel 的包 Fruitcake,就像在基础项目上使用的一样。

//Infrastructur/Http/Kernel.php
    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 = [
            \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
            \Infrastructure\Http\Middlewares\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
            \Fruitcake\Cors\HandleCors::class,
        ];

我尝试在 /public 文件夹中添加 index.php 文件中遗漏的标题。

//public/index.php
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset = UTF-8');

有人知道怎么解决吗?如果需要,我可以添加更多代码。

【问题讨论】:

  • 你的 laravel 版本是什么,因为 laravel 8 已经自带了 cors 中间件
  • 我的 laravel 版本是 laravel8

标签: api cors laravel-8


【解决方案1】:

最后,我找到了解决方案。 我在我的项目中删除了所有与 cors 相关的内容,并将其添加到 public/web.config 文件中:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Headers" value="*" />
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

我在 system.webServer 标记中写了这个,我的项目又开始工作了。

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 2020-10-20
    • 2017-05-09
    • 2020-03-30
    • 2018-12-03
    • 2021-01-01
    • 2020-07-21
    • 2018-07-10
    • 2019-10-03
    相关资源
    最近更新 更多