CORS Error in Laravel 7 using Laravel Lighthouse
Asked Answered
D

1

5

I have an API built with Laravel and Lighthouse-php(for GraphQL). My client is built with Vue js and uses Apollo for the graphQL client-side implementation. Anytime I make a request, I get the following error:

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.

Naturally, I proceeded to install laravel-cors package but I realized afterwards that it came by default with my Laravel installation (7.2.2). Which meant that \Fruitcake\Cors\HandleCors::class was already added to the middleware array in Kernel.php and the cors config file was already in my config directory.

After some googling, I realized that I needed to add \Fruitcake\Cors\HandleCors::class to the route.middleware array in my config/lighthouse.php file

It still did not work. I have restarted the server, cleared cache, cleared config and run composer dump-autoload but I still get the error. I have no idea how to get past this. Any help will be appreciated.

Versions

Laravel 7.2.2

Laravel Lighthouse 4.10

Dragster answered 5/4, 2020 at 22:24 Comment(0)
D
12

I got some help from the folks at lighthouse here. The problem was with my cors configuration. I needed to add graphql to the path array in config/cors but I mistakenly added graphql/*. So the path array looked like this

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

instead of this

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

After making the changes, I run the following: php artisan cache:clear, php artisan config:clear and composer dump-autoload before the CORS error was gone.

The full configuration that worked for me was

return [
    'paths' => ['api/*', 'graphql'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => false,
    'max_age' => false,
    'supports_credentials' => false,
];
Dragster answered 7/4, 2020 at 11:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.