I have fairly simple setup here as described in the code below. But I am not able to get the CORS
to work. I keep getting this error:
XML
Base on jeremiah.trein's answer.
CORS filters are set on server side. Request may work with Postman and fail with a browser because Postman doesn't send preflight request whereas a browser does.
Setting the CORS filters will allow you to configure the origins, methods and headers that the backend shall accept.
In addition, if your browser emits POST or PUT requests that contain a json payload (which is quite reasonnable), you'll need to add 'Content-Type'
to the allowed headers.
Finally the handlers.CORS()(router)
does not only work with the http.ListenAndServe
function but also with http.Handle()
.
The snippet of code might as well look like:
router := mux.NewRouter()
// do all your routes declaration
headersOK := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
originsOK := handlers.AllowedOrigins([]string{"*"})
methodsOK := handlers.AllowedMethods([]string{"GET", "POST", "OPTIONS", "DELETE", "PUT"})
http.Handle("/", handlers.CombinedLoggingHandler(os.Stderr, handlers.CORS(headersOK, originsOK, methodsOK)(router)))
It is worth mentionning that i have successfuly used this snippet of code in a Google Cloud Platform Standard AppEngine (and I believe it would work in a Flex AppEngine as well).