0

I'm using Laravel to serve a GraphQL API, using Lighthouse. Everything works fine when I use grapqhl as a URI in the main domain, but when I use it in a subdomain eg. grapql.app.test I get the next error:

Access to fetch at 'http://graphql.app.test/' from origin 'http://app.test' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'

My config\cors:

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

How can I solve this?

I'm using laravel 8.

exsnake
  • 1,767
  • 2
  • 23
  • 44
  • I dont know why the * doesnt worked for me. Here it works when I define the origin. ```'allowed_origins' => ['http://app.test'],```. Is the path you are trying to access inside one of the paths you defined? This URI is root ```http://graphql.app.test/```, what happens when you try to access ```http://graphql.app.test/api``` ? – Jonathan Martins Sep 14 '20 at 20:05
  • @JonathanMartins I have my API running in `http://graphql.app.test/`and I try to use it in `http://app.test`. There's where I get the CORS error. I tried to add `http://app.test` to `allowed_origins` but didn't work. – exsnake Sep 14 '20 at 20:19
  • If you make an ajax request from ```http://app.test``` to ```http://graphql.app.test/api``` what you get? – Jonathan Martins Sep 14 '20 at 20:26
  • @JonathanMartins I get the same error – exsnake Sep 14 '20 at 20:33
  • @JonathanMartins ok, the solutio was add `'\'` to `paths` and `'*'` to `allowed_origins`. Also works if I use this `'allowed_origins' => ['http://app.test'],`. Thanks! – exsnake Sep 14 '20 at 21:08

2 Answers2

1

Incase someone is facing this issue with Laravel 8+, ensure that the API URL doesn't end with a slash on the client request i.e. instead of https://someapi/endpoint/ it should be https://someapi/endpoint

0

If anyone is having trouble with this, you need to add the paths that you will use. In my case was / due that my API is in grapql.app.test.

The resulting code:

'paths' => ['api/*','graphql','/'],
'allowed_methods' => ['*'],
'allowed_origins' => ['http://app.test'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
exsnake
  • 1,767
  • 2
  • 23
  • 44