In all three cases, Dgraph is running in Docker on localhost:8080 and React is running on localhost:3000. In all three cases I couldn’t create mutations through the React app because I got these errors in the Chrome developer tools:
Access to fetch at ‘http://localhost:8080/graphql’ from origin ‘http://localhost:3000’ 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.
I think I’m missing something basic about Docker or networking. I researched CORS errors and it looks like the required header must be sent from the server, but as far as I can tell, I don’t have the ability to add those headers to the responses coming from the Dgraph side.
Can anyone see the problem with my setup?
edit: The interesting thing is that this tutorial Building a To-Do List React App with Dgraph - Dgraph Blog sets up Dgraph with docker-compose, and it does let me do mutations, but not modify the schema with curl -X POST localhost:8080/admin/schema --data-binary '@schema.graphql'.
When the standalone docker version of Dgraph is used with the app from that tutorial, instead of the docker-compose version, I can modify the schema, but the above CORS errors come up.
chewxy The Chrome plugin didn’t work for me. I tried enabling CORS, then testing the requests with the plugin as shown in the screenshots below. But the requests were still blocked.
@MichelDiz I don’t think that removing docker would mitigate this impact. CORS is between your browser and dgraph, so docker or not has no impact.
@catherineluse, could you share the snippet you are using to connect to the db, specifically, which HTTP library? You mentioned react, so I assume you are probably using fetch or axios or something similar?
Do note that the Request to fetch the data must be over POST for CORS to kick in (as you can see in the Access-Control-Allow-Methods). I believe we do support GET as well, but it looks like GET requests don’t work with CORS.
Here is an example that should work (run this in the browser console)
You should see some types and such logged. If this doesn’t work, could you let us know what happened in both the console tab, as well as the network tab (you should see two network requests: an OPTIONS request, followed by a POST request)
I’m pretty sure about what I’m saying. CORS is about the origin of the assets. If you are running Dgraph on Docker and the React locally. Even if you are using “localhost” - It is a “cross-origin” unless you are using some reverse proxy. If you run all locally (or all in docker), it works just fine.