I wrote a simple API with the Gorilla Web Toolkit, handling the CORS answers through its handlers:
r := mux.NewRouter()
r.HandleFunc("/api/note", readHandler).Methods("GET")
r.HandleFunc("/api/note", writeHandler).Methods("POST")
r.HandleFunc("/api/note", deleteHandler).Methods("DELETE")
r.HandleFunc("/api/note", optionsHandler).Methods("OPTIONS")
optionsHandler is
func optionsHandler(_ http.ResponseWriter, _ *http.Request) {
return
}
My rationale behind this is that a Preflight call will use OPTIONS
but the only thing it is interested in are the relevant CORS headers.
GET
and POST
work fine, a JavaScript fetch()
call goes through with the right headers.
DELETE
however fails on the Preflight call: Chrome DevTools states that a DELETE + Preflight
call fails with CORS error
, the next line is the Preflight OPTIONS
call that fails with a 405 ("Method Not Allowed")
Why do I get this error when the method is handled? And how to fix it?
I fixed the issue by updating the CORS()
call:
methods := handlers.AllowedMethods([]string{"OPTIONS", "DELETE", "GET", "HEAD", "POST", "PUT", "PATCH"})
origins := handlers.AllowedOrigins([]string{"*"})
headers := handlers.AllowedHeaders([]string{"Content-Type"})
log.Fatal(http.ListenAndServe("127.0.0.42:80", handlers.CORS(methods, origins, headers)(r)))
I think (but I am not sure) that what actually fixed the call is the headers
entry.