[英]Go: How to disable CORS using gqlgen graphql implementation?
I am using gqlgen as GraphQL server.我使用gqlgen作为 GraphQL 服务器。 I connect to this server from the front end application using Apollo client .
我使用Apollo 客户端从前端应用程序连接到此服务器。
Everything works correctly if I compile the front end code and serve it as static content by the GraphQL server.如果我编译前端代码并将其作为静态内容由 GraphQL 服务器提供,则一切正常。
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
.在开发过程中,我的基于 Go 的 GraphQL API 在
http://localhost:8080
上运行,我在http://localhost:3000
上运行的单独服务器上有前端代码。 This way I get CORS errors.这样我就会收到 CORS 错误。
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.我设法通过在创建客户端时指定
no-cors
选项来解决前端方面的问题,但后端仍然为我的请求提供 400s。
Question:题:
How to disable CORS in a gqlgen-based GraphQL API?如何在基于 gqlgen 的 GraphQL API 中禁用 CORS?
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 .完整的服务器端代码可在 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.
我在 StackOverflow 上检查了几个解决方案,比如这个,但是它们提供了一个库特定的解决方案,在我的情况下不适用。
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.此外,我认为最好在开发以外的环境中进行相应的调整。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.