Search code examples
httpgocorsgo-chi

CORS not working even though OPTIONS returns HTTP 200


I am using chi and have setup cors as follows

func main() {
    r := chi.NewRouter()
    r.Use(render.SetContentType(render.ContentTypeJSON))
    r.Use(Cors)

    r.Post("/auth/login", Login)
    r.Route("/ec2", func(r chi.Router) {
        r.Use(Cors)
        r.Get("/", ListEc2)
    })

    http.ListenAndServe(":9000", r)
}

My Cors middleware

func Cors(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Allow-Control-Allow-Origin", "*")
        w.Header().Set("Allow-Control-Allow-Methods", "*")
        w.Header().Set("Allow-Control-Allow-Headers", "*")
        w.Header().Set("Allow-Control-Allow-Credentials", "true")
        log.Printf("Should set headers")

        if r.Method == "OPTIONS" {
            log.Printf("Should return for OPTIONS")
            return
        }
        next.ServeHTTP(w, r)
    })
}

In network tab it looks like:

enter image description here


Solution

  • You just mistyped the header names:

    w.Header().Set("Allow-Control-Allow-Origin", "*")
                    ^^^^^
    

    Instead of Allow-Control there, you need Access-Control:

    w.Header().Set("Access-Control-Allow-Origin", "*")
    

    …and same of course for the other three headers you’re setting there.