Dylan Meeus
Dylan Meeus

Reputation: 5802

golang preflight request error

I have set up my Go backend using gorilla/mux and rs/cors. When I try to send a request including a custom header (Bearer) it fails.

My server setup looks like this:

     router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/users", GetUsers).Methods("GET")
router.HandleFunc("/", GetUsers).Methods("GET")
router.HandleFunc("/tweets", GetTweets).Methods("GET")
router.HandleFunc("/login", Login).Methods("POST")
router.HandleFunc("/profile/tweets", ProfileTweets).Methods("GET")

c := cors.New(cors.Options{
    AllowedOrigins: []string{"*"},
    AllowedMethods: []string{"GET", "POST", "PATCH"},
    AllowedHeaders: []string{"Bearer", "Content_Type"},})

handler := c.Handler(router)
log.Fatal(http.ListenAndServe(":8080", handler))

I have tried various other solutions (such as adding OPTIONS in the Methods call. The endpoint for which I am trying to pass the Bearer token is the /profile/tweets endpoint.

I'm unsure how to continue with gorilla/mux and rs/cors in terms of adding the preflight request.

The actual error that I get:

Fetch API cannot load http://localhost:8080/profile/tweets. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Thanks!

Upvotes: 3

Views: 3636

Answers (1)

Dylan Meeus
Dylan Meeus

Reputation: 5802

I've just solved the problem. I had a typo in the AllowedHeaders as pointed out by @Francois P.

In addition, I had to add OptionsPassthrough and the OPTIONS method, like so:

     router.HandleFunc("/profile/tweets", ProfileTweets).Methods("GET","OPTIONS")

c := cors.New(cors.Options{
    AllowedMethods: []string{"GET","POST", "OPTIONS"},
    AllowedOrigins: []string{"*"},
    AllowCredentials: true,
    AllowedHeaders: []string{"Content-Type","Bearer","Bearer ","content-type","Origin","Accept"},
    OptionsPassthrough: true,
})

Upvotes: 7

Related Questions