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?
i deployed my graphql api on GAE. when try to connect with local create react app on localhost:3000 i keep getting:
Access to fetch at ‘https://MyApi/api’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: 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.
Hello @dumadi, your API use Elixir? In my case, I solved that problem using [cors_plug]. I had an umbrella project (as my API), and I put that plug inside the project with the endpoint.
I modified the Router, something like this:
defmodule APIWeb.Router do
use APIWeb, :router
pipeline :any_name do
plug CORSPlug, origin: "*"
...
end
scope "/" do
...
pipe_through(:any_name)
...
end
end
I’m having a problem with CORS. Via the browser, I am getting the following error:
Access to XMLHttpRequest at 'http://localhost:4000/api/data' from origin 'http://localhost:4200' 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 currently believe I have my setup similar to the example above:
pipeline :api do
plug CORSPlug, origin: "*"
plug :accepts, ["json"]
forward "/", Absinthe.Plug, schema: DxAppRcWeb.Schema
end
I can replicate the same query using GraphiQL and it works - so I know my pipeline is configured correctly when CORS isn’t an issue. Any suggestions for how I should troubleshoot?
To answer my own problem, the pipeline that I added the CORS logic to was downstream of Phoenix.Router, meaning it never got called. Moving the plug upstream out of the router.ex file into the endpoint.ex file solved the problem.