Problem with CORS - request failed, has been blocked by CORS policy

I’m doing requests with Graphql and Apollo Client to a backend project made with Phoenix. I had a problem because the request failed and the Chrome console shows me the error “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.”

I used CORSICA and CORSPlug to allow access but it didn’t work. Please, anyone has an example or solved that error?

Thanks!

How did You configure CORS? I had to update my endpoint to make it work (with Corsica).

Something like this…

  plug Corsica,
    origins: [
      "http://localhost:4000",
      "http://localhost:8000",
      "http://localhost:8080"
    ],
    allow_headers: ["accept", "content-type", "authorization"],
    allow_credentials: true,
    log: [rejected: :error, invalid: :warn, accepted: :debug]

Of course your configuration may vary a lot…

2 Likes

Have you tried to handle OPTIONS query?

If you need to handle requests from different domain, your server should allow to do it.

Here is an example of nginx.conf

    location / {
        if ($request_method = OPTIONS) {
            add_header Access-Control-Allow-Origin $http_origin;
            add_header Access-Control-Allow-Credentials true;
            add_header Access-Control-Allow-Headers "Authorization, Origin, Content-Type, Accept";
            add_header Access-Control-Allow-Methods "GET, PUT, POST, DELETE, PATCH, OPTIONS";
            add_header Content-Length 0;
            add_header Content-Type text/plain;
            return 200;
        }

        proxy_pass http://backend:4000;
    }

I’m going to try that. I didn’t configure the allow Headers, thanks!

I did only that:
plug Corsica, origins: "*", allow_credentials: true

Could you pass me another example to add that? This is my first time doing that.