A fellow developer and I were experiencing a weird issue with our application in the past couple of days. Specifically, he's writing the API and I'm writing the web front end. Since the UI runs from a different port, we have to setup CORS in the application so that the UI could make requests into the API.
I'll not go into great detail but this is the first project where I've had to heavily engage CORS. Specifically, our problem was related to the UI code sending JSON data as the request body and specifying in the header a content type of
application/json. Since this isn't an acceptable content type within CORS, the preflight rejected the request.
At the time neither of us were aware of preflight requests and I had assumed my
fetch(...) calls were modifying my headers and dropping my data. After finally digging into the mechanics of CORS, we were able to discern that the problem was with the preflight request receiving a response stating that my content-type wasn't accepted.
after we fixed our issue, I couldn't help but wonder what was the purpose of the preflight check. Specifically, this doesn't benefit to browser/UI. You should an error when you make a request that isn't accepted by CORS and the response from the server can relay this specifics of why your request isn't needed. In other words, you could skip a preflight check and just rely on the response from the server to dictate whether the request is correct, and this saves the browser from making two requests for the single call.
Preflight checks also don't benefit the server. The server should reject any request that doesn't match the CORS requirements, regardless of whether a preflight call has been made or not.
So, what's the point of the preflight? Why is it proper for the browser to make to calls, instead of one, when the default allowable CORS header properties are different than what's being requested by the client?