When making AJAX POST requests using jQuery, it is possible to include custom headers to control the request's behavior. However, it is crucial to understand the role of Access-Control Request Headers (CORS) in cross-origin requests.
By default, jQuery prefaces cross-origin requests with an OPTIONS request to initiate a pre-flight check. This check ensures that the server allows the specific HTTP method and headers included in the original request. During this pre-flight check, jQuery automatically adds the Access-Control-Request-Headers header to the request, which specifies the custom headers present in the original request.
In the example provided:
$.ajax({ ... headers: { "My-First-Header":"first value", "My-Second-Header":"second value" } ... })
The request parameters include two custom headers. When the pre-flight check is initiated, the browser automatically modifies the request headers to the following:
... Access-Control-Request-Headers: My-First-Header,My-Second-Header ...
This ensures that the server is aware of the custom headers to be included in the actual POST request. However, the custom headers themselves are not present in the pre-flight check request.
To include the custom headers in the actual POST request, you can use the beforeSend function as follows:
$.ajax({ ... beforeSend: function(xhr) { xhr.setRequestHeader("My-First-Header", "first value"); xhr.setRequestHeader("My-Second-Header", "second value"); } ... })
In this case, the custom headers will be included in the POST request directly, without triggering a pre-flight check. Note that for cross-origin requests, the server must explicitly allow the specified headers in its Access-Control-Allow-Headers response header.
The above is the detailed content of How do I include custom headers in an AJAX POST request without triggering a pre-flight check?. For more information, please follow other related articles on the PHP Chinese website!