Answer the question
In order to leave comments, you need to log in
How to defeat OPTIONS on CORS?
That's the day I'm trying to win CORS
.
There is a project that I turn on localhost
and turn to from it REST
. The entire Internet has rustled, it seems that all the headers on both sides are correctly indicated ( Authorization Bearer
), but it does not work.
When sending a request to the server, the first thing is sent OPTIONS
(after which, as far as I understand from the documentation, it should follow POST
, but this does not happen). OPTIONS
sent, status 200
and it has response. Now, if you reload the page, then POST
requests are already sent.
Who knows the solutions to the problem?
Answer the question
In order to leave comments, you need to log in
Just yesterday I figured it out for my debt tracking project https://debtstracker.io/ and won.
OPTIONS should return 200 with headers and an empty response.
I was guided by this scheme :
Here is my working Go code:
func getOnly(handler HttpHandler) HttpHandler {
return func(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
if r.Method == "OPTIONS" { // Preflight request
origin := r.Header.Get("Origin")
switch origin {
case "http://localhost:8080":
case "http://localhost:8100":
case "https://debtstracker.local":
case "https://debtstracker.io":
case "":
BadRequest(c, w, errors.New("Missing required request header: Origin"))
return
default:
err := errors.New(fmt.Sprintf("Unknown origin: %v", origin))
log.Debugf(c, err.Error())
BadRequest(c, w, err)
return
}
log.Debugf(c, "Request 'Origin' header: %v", origin)
if accessControlRequestMethod := r.Header.Get("Access-Control-Request-Method"); accessControlRequestMethod != "GET" {
BadRequest(c, w, errors.New("Not a valid preflight request"))
return
}
responseHeader := w.Header()
responseHeader.Set("Access-Control-Allow-Methods", "GET")
if accessControlRequestHeaders := r.Header.Get("Access-Control-Request-Headers"); accessControlRequestHeaders != "" {
log.Debugf(c, "Request Access-Control-Request-Headers: %v", accessControlRequestHeaders)
responseHeader.Set("Access-Control-Allow-Headers", accessControlRequestHeaders)
} else {
log.Debugf(c, "Request header 'Access-Control-Allow-Headers' is empty or missing")
// TODO(security): Is it wrong to return 200 in this case?
}
responseHeader.Set("Access-Control-Allow-Origin", origin)
w.WriteHeader(200)
return
}
if r.Method != "GET" {
BadRequest(c, w, errors.New(fmt.Sprintf("Expecting to get request method GET, got: %v", r.Method)))
return
}
handler(w, r)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question