2

According to the fetch specs it appears that as long as a Content-Type is specified that is one of "application/x-www-form-urlencoded", "multipart/form-data", or "text/plain" and other conditions are satisfied then a POST request should not result in a preflight request. In practice however I've had a difficult time specifying multiple headers for fetch in a way that doesn't cause the OPTIONS request for the preflight check.

ex 1.

fetch("https://differentsubodmain.example.com/api/resource", {
    headers: {
        "Content-Type": "text/plain, application/json",
        Accept: "application/json"
    },
    method: "POST",
    body: JSON.stringify({})
})

ex 2.

var myHeaders = new Headers();
myHeaders.append('Accept', 'application/json');
myHeaders.append('Content-Type', 'text/plain');
myHeaders.append('Content-Type', 'application/json');

fetch("https://differentsubodmain.example.com/api/resource", {
    headers: myHeaders,
    method: "POST",
    body: JSON.stringify({})
})

ex 3.

fetch("https://differentsubodmain.example.com/api/resource", {
    headers: [
        ["Content-Type", "application/json"],
        ["Content-Type", "text/plain"],
        ["Accept", "application/json"]
    ],
    method: "POST",
    body: JSON.stringify({})
    })

Neither of these examples succeed in requesting without the preflight request but specifying either with only "Content-Type": "text/plain" appears to work just fine. The example here however shows both being specified in a request and suggests that it shouldn't cause a preflight. Is this just an issue with different browser implementations or am I missing something?

jpierson
  • 13,736
  • 10
  • 94
  • 137
  • 1
    Does it matter that your headers is an object instead of an array of arrays as in the example? Specs say it's a list, not object. – Train Jun 28 '19 at 19:21
  • Both ways appear to work in general however neither seems to give us leeway with regard to the CORS preflight requirement. – jpierson Jun 28 '19 at 19:44
  • Does this answer your question? [Why is there no preflight in CORS for POST requests with standard content-type](https://stackoverflow.com/questions/39725955/why-is-there-no-preflight-in-cors-for-post-requests-with-standard-content-type) – Vadzim Feb 03 '20 at 15:23

1 Answers1

3

It looks like perhaps I hadn't read that reference carefully. Below is the important excerpt.

Warning. This intentionally does not use extract a MIME type as that algorithm is rather forgiving and servers are not expected to implement it.

If extract a MIME type were used the following request would not result in a CORS preflight and a naïve parser on the server might treat the request body as JSON

It looks like we are largely constrained to the mime types application/x-www-form-urlencoded, multipart/form-data, or text/plain to avoid preflight requests for CORS.

Reference:

Community
  • 1
  • 1
jpierson
  • 13,736
  • 10
  • 94
  • 137