Gqlgen: cors origin error in using gqlgen

Created on 12 Sep 2020  路  2Comments  路  Source: 99designs/gqlgen

Hey,I want to use this project in the react app but i get cors origin error

Access to fetch at 'http://localhost:8080/' from origin 'http://localhost:3000' 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.

Base on document for cors i write this but i gt error in the client react app

This is my server.go base on document for cors

const defaultPort = "8080"

func main() {
    port := os.Getenv("PORT")
    if port == "" {
        port = defaultPort
    }

    router := chi.NewRouter()
    router.Use(cors.New(cors.Options{
        AllowedOrigins:   []string{"http://localhost:8080"},
        AllowCredentials: true,
        Debug:            true,
    }).Handler)
    router.Use(auth.Middleware())


    mysql.InitDB()
    mysql.Migrate()
    server := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{}}))
    server.AddTransport(&transport.Websocket{
        Upgrader: websocket.Upgrader{
            CheckOrigin: func(r *http.Request) bool {
                // Check against your desired domains here
                return r.Host == "http://localhost:3000/"
            },
            ReadBufferSize:  1024,
            WriteBufferSize: 1024,
        },
    })
    http.Handle("/", playground.Handler("GraphQL playground", "/query"))
    http.Handle("/query", server)

    log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
    log.Fatal(http.ListenAndServe(":"+port, nil))
}

Most helpful comment

Please use stackoverflow for this kind of questions.

All 2 comments

Please use stackoverflow for this kind of questions.

Change

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

to

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

and also pass the router to http.ListenAndServe

Was this page helpful?
0 / 5 - 0 ratings

Related issues

huanghantao picture huanghantao  路  3Comments

itsbalamurali picture itsbalamurali  路  4Comments

cemremengu picture cemremengu  路  3Comments

ksoda picture ksoda  路  3Comments

bieber picture bieber  路  4Comments