Home > Web Front-end > JS Tutorial > How do I include custom headers in an AJAX POST request without triggering a pre-flight check?

How do I include custom headers in an AJAX POST request without triggering a pre-flight check?

Susan Sarandon
Release: 2024-11-07 19:08:02
Original
535 people have browsed it

How do I include custom headers in an AJAX POST request without triggering a pre-flight check?

Access-Control Request Headers: Understanding the Pre-flight Check

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"
    }
    ...
})
Copy after login

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
...
Copy after login

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");
    }
    ...
})
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template