gocorsgqlgen

how to enable gqlgen server for CORS issue?


GOAL:

Svelte app running on port 5000 wants to query data from gqlgen GraphQL server running on port 8080, both on localhost. I tried to query a public graphql API such as https://api.react-finland.fi/graphql just to test if my Svelte app (port:5000) is working well and it is. So I think the problem lies with my Go graphql server (port:8080).

SYSTEM

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
)

HAVE TRIED

According to the official site, I have tried their approach.

And here is my code:

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)
    }
}

RESULT

I got those errors:

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.

HOW TO SOLVE?

I've read quite some documentation and googled around... but couldn't figure out exactly how to and I don't know how to debug to find solution. I just learnt GO for two days so far. Can someone help? Thanks!


Solution

  • Hi now someone helped me find out the major problems I have:

    1.Yes, we can use just one in the line where I wrote :

    AllowedOrigins:   []string{"http://localhost:5000", "http://localhost:8080"},
    AllowOriginFunc:  func(origin string) bool { return true },
    

    In fact the second one will overwrite the first one, so can choose just one.

    2.In this part

    log.Fatal(http.ListenAndServe(":"+port, nil))
        err := http.ListenAndServe(":8080", router)
        if err != nil {
            panic(err)
        }
    

    I have written the http:ListenAndServe twice, so it didn't get to the second one. I deleted the log.Fatal(http.ListenAndServe(":"+port, nil))

    3.Since we passed the middleware to router for http request, we need to use that instead of http.handle. So those two lines were wrong:

    http.Handle("/", playground.Handler("GraphQL playground", "/query"))
    http.Handle("/query", srv)
    

    The right way to do it should be :

    router.Handle("/", playground.Handler("GraphQL playground", "/query"))
    router.Handle("/query", srv)
    

    In fact that was shown in the official approach... but somehow after I tried several different solutions I got lost in the rabbit holes and didn't see those obvious errors! >.<

    After the above changes now it works finally! Thanks for your help!