Go语言 gqlgen CORS拒绝来自http://localhost:3000的连接

xe55xuns  于 2023-03-27  发布在  Go
关注(0)|答案(1)|浏览(164)

我尝试使用官方文档中的代码将CORS添加到我的gqlgen服务器,但是当我尝试从http://localhost:3000连接到服务器时,连接被拒绝。

package main

import (
    "log"
    "net/http"
    "os"

    "github.com/99designs/gqlgen/graphql/handler"
    "github.com/99designs/gqlgen/graphql/handler/transport"
    "github.com/99designs/gqlgen/graphql/playground"
    "github.com/go-chi/chi"
    "github.com/gorilla/websocket"
    "github.com/megajon/gqlgen-cors/graph"
    "github.com/rs/cors"
)

const defaultPort = "8081"

func main() {
    port := os.Getenv("PORT")
    if port == "" {`your text`
        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:3000"},
        AllowCredentials: true,
        Debug:            true,
    }).Handler)

    srv := handler.NewDefaultServer(graph.NewExecutableSchema(graph.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("/query", srv)

    log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
    err := http.ListenAndServe(":"+port, router)
    if err != nil {
        panic(err)
    }
}
jfgube3f

jfgube3f1#

事实证明,问题不是CORS,而是gqlgen API从Windows Powershell运行,前端应用程序从wsl ubuntu终端运行。这本质上是两个独立的网络。一旦我在同一环境中运行两个应用程序,问题就解决了。

相关问题