I am using gqlgen as GraphQL server. I connect to this server from the front end application using Apollo client .
Everything works correctly if I compile the front end code and serve it as static content by the GraphQL server.
Problem:
During development I have my Go-based GraphQL API running on http://localhost:8080
and I have the front end code on a separate server runing on http://localhost:3000
. This way I get CORS errors.
I managed to fix the issue on the front end side by specifying no-cors
option while creating the client, but the back end still gives 400s to my requests.
Question:
How to disable CORS in a gqlgen-based GraphQL API?
Code:
config := gql.Config{Resolvers: &gql.Resolver{}}
handler := handler.GraphQL(gql.NewExecutableSchema(config))
http.Handle("/query", handler)
http.ListenAndServe(":8080", nil)
The full server side code is available on GitHub .
What I've tried :
I followed the solution from the documentation which didn't work. I checked a couple of solutions on StackOverflow, like this one , however they give a library specific solutions which don't feet in my case.
I think that it should be just enough if you set up this simple middleware
func cors(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
h(w, r)
}
}
...
http.Handle("/query", cors(handler))
...
Also, I think it would be good to tune this accordingly on environments other than development.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.