使用 Laravel 灯塔 Laravel 7 中的 CORS 错误

CORS Error in Laravel 7 using Laravel Lighthouse

我有一个 API 使用 Laravel 和 Lighthouse-php(用于 GraphQL)构建。我的客户端是用 Vue js 构建的,并使用 Apollo 来实现 graphQL 客户端。每当我发出请求时,我都会收到以下错误:

Access to fetch at 'http://localhost:8000/graphql' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

当然,我继续安装 laravel-cors 包,但后来我意识到它是我的 Laravel 安装 (7.2.2) 默认附带的。这意味着 \Fruitcake\Cors\HandleCors::class 已经添加到 Kernel.php 的中间件数组中,并且 cors 配置文件已经在我的配置目录中。

谷歌搜索后,我意识到我需要将 \Fruitcake\Cors\HandleCors::class 添加到 config/lighthouse.php 文件中的 route.middleware 数组

还是不行。我已经重新启动服务器,清除缓存,清除配置和 运行 composer dump-autoload 但我仍然收到错误。我不知道如何克服这个问题。任何帮助将不胜感激。

版本

Laravel 7.2.2

Laravel 灯塔 4.10

我从灯塔 here 的人那里得到了一些帮助。问题出在我的 cors 配置上。我需要将 graphql 添加到 config/cors 中的路径数组,但我错误地添加了 graphql/*。所以路径数组看起来像这样

'paths' => ['api/*', 'graphql/*'],

而不是这个

'paths' => ['api/*', 'graphql'],

进行更改后,我 运行 以下内容: 在 CORS 错误消失之前 php artisan cache:clearphp artisan config:clearcomposer dump-autoload

对我有用的完整配置是

return [
    'paths' => ['api/*', 'graphql'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => false,
    'max_age' => false,
    'supports_credentials' => false,
];