目标:
运行在 5000 端口上的 Svelte 应用程序想要从运行在 8080 端口上的 gqlgen GraphQL 服务器查询数据,两者都在 localhost 上。我尝试查询公共 graphql API,例如https://api.react-finland.fi/graphql 只是为了测试我的 Svelte 应用程序(端口:5000)是否运行良好并且确实如此。所以我认为问题出在我的 Go graphql 服务器(端口:8080)上。
系统
go version
go version go1.15 linux/amd64
go 1.15
require (
github.com/99designs/gqlgen v0.12.1
github.com/go-chi/chi v4.1.2+incompatible
github.com/gorilla/websocket v1.4.2
github.com/rs/cors v1.7.0
github.com/vektah/gqlparser/v2 v2.0.1
)
试过
根据官方网站,我已经尝试过他们的方法。
这是我的代码:
func main() {
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}
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:5000", "http://localhost:8080"},
AllowOriginFunc: func(origin string) bool { return true },
AllowedMethods: []string{},
AllowedHeaders: []string{},
AllowCredentials: true,
Debug: true,
}).Handler)
srv := handler.NewDefaultServer(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 == "localhost:8080"
},
ReadBufferSize: 1024,
WriteBufferSize: 1024,
},
})
http.Handle("/", playground.Handler("GraphQL playground", "/query"))
http.Handle("/query", srv)
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
err := http.ListenAndServe(":8080", router)
if err != nil {
panic(err)
}
}
结果
我得到了这些错误:
Access to fetch at 'http://localhost:8080/' from origin 'http://localhost:5000' 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.
怎么解决?
我已经阅读了相当多的文档并在谷歌上搜索了......但无法弄清楚究竟如何,我不知道如何调试以找到解决方案。到目前为止,我刚学了两天的 GO。有人可以帮忙吗?谢谢!