Preflight request is sent with all methods

前端 未结 2 1132
醉梦人生
醉梦人生 2020-12-15 09:31

My FE application is using API from different domain. I know that it should trigger CORS, but as I understood it shouldn\'t create preflight for every request.

Accor

2条回答
  •  无人及你
    2020-12-15 10:03

    See https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests

    A CORS preflight OPTIONS request can be triggered just by adding a Content-Type header to a request — if the value’s anything except application/x-www-form-urlencoded, text/plain, or multipart/form-data. And that’s true even for GET requests (though you should never add a Content-Type header to a GET — because there’s no request body, so it serves no purpose).

    And among the headers shown in the question, the Authorization header will also trigger a preflight, as will the "Language" header (which isn’t even a standard header name; maybe that was intended to be Accept-Language?), and the Access-Control-Allow-Origin header (which isn’t even a request header; it’s a response header that should never be used in frontend code).

    As far as the headers that don’t trigger a preflight: the Fetch spec (which defines CORS behavior) specifies what it calls a CORS-safelisted request-header, which it defines as one of:

    • Accept
    • Accept-Language
    • Content-Language
    • Content-Type whose value, once parsed, has a MIME type (ignoring parameters) that is application/x-www-form-urlencoded, multipart/form-data, or text/plain

    Any request — including any GET request — which contains a header that’s not among those CORS-safelisted request-headers listed above will trigger a preflight.


    To help make all that more clear, I updated the MDN documentation about CORS “simple requests” and the MDN documentation about CORS preflighted requests (it’s slightly more complicated than what’s described above, actually—but what’s above suffices for the context of this question).


    Note that WebKit/Safari places additional restrictions on the values allowed in the Accept, Accept-Language, and Content-Language headers.

    If any of those headers have ”non-standard” values, WebKit/Safari will do a preflight.

    As far as what WebKit/Safari considers “non-standard” values for those headers, that’s not really documented except in the following WebKit bugs:

    • Require preflight for non-standard CORS-safelisted request headers Accept, Accept-Language, and Content-Language
    • Allow commas in Accept, Accept-Language, and Content-Language request headers for simple CORS
    • Switch to a blacklist model for restricted Accept headers in simple CORS requests

    No other browsers implement those extra restrictions, because they’re not part of the spec. They were unilaterally added to WebKit without any discussion with the spec editor or other browsers.

提交回复
热议问题