我正在尝试使用 React 设置基本堆栈,Apollo 由 Go through gqlgen 提供的 graphQL 提供服务。
我正在关注 getting started gqlgen 指南,工作正常。
我也在关注 getting started阿波罗指南,工作正常。
我的问题在于当我尝试将两者拼接在一起时,chrome 不允许我 ping 后端。考虑到 React 是在 localhost:3000
上,我收到了一个 CORS 预检标题错误,这是可以理解的Go 服务器在 localhost:8080
上
gqlgen 提供了一个关于如何在 Go 服务器上运行 CORS 的有用示例 here使用 chi 和 go-cors。但是,提供的示例基于 星球大战 gqlgen 的示例而不是 入门例子。
我将 CORS 示例修改为以下内容:
package main
import (
"net/http"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/handler/transport"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/FlockSupport/graphql/graph"
"github.com/FlockSupport/graphql/graph/generated"
"github.com/go-chi/chi"
"github.com/gorilla/websocket"
"github.com/rs/cors"
)
func main() {
router := chi.NewRouter()
// Add CORS middleware around every request
// See https://github.com/rs/cors for full option listing
router.Use(cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:8080"},
AllowCredentials: true,
Debug: true,
}).Handler)
// srv := handler.New(starwars.NewExecutableSchema(starwars.NewResolver())) // MODIFIED THIS.
srv := handler.New(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{}}))
srv.AddTransport(&transport.Websocket{
Upgrader: websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
// Check against your desired domains here
return r.Host == "example.org"
},
ReadBufferSize: 1024,
WriteBufferSize: 1024,
},
})
router.Handle("/", playground.Handler("GraphQL Playground", "/query"))
// router.Handle("/", handler.Playground("Starwars", "/query")) // MODIFIED THIS.
router.Handle("/query", srv)
err := http.ListenAndServe(":8080", router)
if err != nil {
panic(err)
}
}
服务器运行,但通过 Playground 测试查询(localhost:8080 所以 CORS 在这里无关紧要)给出以下错误:
{
"error": {
"errors": [
{
"message": "transport not supported"
}
],
"data": null
}
}
即使我只设置了 Chi 路由器,这也不起作用:
func main() {
router := chi.NewRouter()
srv := handler.New(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{}}))
router.Handle("/", playground.Handler("GraphQL Playground", "/query"))
router.Handle("/query", srv)
err := http.ListenAndServe(":8080", router)
if err != nil {
panic(err)
}
}
我得到一个
Server Cannot Be Reached
当我访问 localhost:8080 游乐场时。如何在 gqlgen Go 服务器上正确启用 CORS 以便 React 可以对其进行 ping 操作?
最佳答案
您需要提供 CORS 检查作为中间件。
例如,您可以使用“github.com/rs/cors”。它可能看起来像下面的代码
mux.Handle("/playground", handler.Playground("API", "/gql"))
mux.Handle("/gql",
handler.GraphQL(
gen.NewExecutableSchema(gen.Config{Resolvers: resolver.New(dep)}),
handler.ErrorPresenter(errorCustomize)))
h := cors.AllowAll().Handler(util.JwtMiddleware(mux))
srv := &http.Server{
Addr: ":8087",
Handler: h,
}
关于go - 将 CORS header 添加到 gqlgen 默认示例中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60900651/