Describe the bug
I keep getting a CORS error despite following this solution where \Fruitcake\Cors\HandleCors::class was added to middlewares in the lighthouse config file.
Expected behavior/Solution
I expected the CORS error to be gone after adding laravel-cors to the lighthouse config but the probem persists.
Steps to reproduce
\Fruitcake\Cors\HandleCors::class to route->middleware in config\lighthouseOutput/Logs
Click to expand
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.
Environment
Lighthouse Version: 4.10.2
Laravel Version: 7.2.2
This comment suggests that the OPTIONS method may be the culprit here. Can you check which exact request is triggering the error?
Ye, I also tip for the OPTIONS request to fail here. Try to add \Fruitcake\Cors\HandleCors::class to $middleware in App\Http\Kernel instead.
Don't forget to add your graphql route to pahts in config/cors.php. Also configure allowed origins, for testing you can take ['*']. Here is my working example of config/cors.php:
return [
'paths' => ['api/*', 'graphql'],
'allowed_methods' => ['*'],
'allowed_origins' => explode(',', env('ALLOWED_CORS_ORIGINS', [])),
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
@lorado can you review https://github.com/nuwave/lighthouse/pull/1267 ?
@lorado @spawnia Thanks for the response. You are right. The problem was with OPTIONS. \Fruitcake\Cors\HandleCors::class was already in $middleware in App\Http\Kernel but I made a mistake of adding graphql/* to paths in the cors config instead of graphql. The forward slash caused the problem.
For the convenience of future readers, here is my old cors config:
return [
'paths' => ['api/*', 'graphql/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => false,
'max_age' => false,
'supports_credentials' => false,
];
This is the new one that works
return [
'paths' => ['api/*', 'graphql'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => false,
'max_age' => false,
'supports_credentials' => false,
];
Thanks for the assistance
@crazyabdul as described in #1267 it works also with 'graphql', so without * at the end. Actually lighthouse is bound to /graphql route only
@lorado I have updated my answer