Home > Web Front-end > JS Tutorial > How to Send Custom Headers in AJAX POST Requests with jQuery?

How to Send Custom Headers in AJAX POST Requests with jQuery?

Patricia Arquette
Release: 2024-11-05 11:45:02
Original
945 people have browsed it

How to Send Custom Headers in AJAX POST Requests with jQuery?

Custom Headers in AJAX POST Requests with jQuery

In AJAX POST requests initiated with jQuery, it is possible to include custom headers. However, the mechanism for adding headers differs from the typical approach.

When you specify headers as shown in the example:

$.ajax({
    type: 'POST',
    url: url,
    headers: {
        "My-First-Header":"first value",
        "My-Second-Header":"second value"
    }
}).done(function(data) {
    alert(data);
});
Copy after login

Understandably, you would expect the headers to be sent as:

My-First-Header: first value
My-Second-Header: second value
Copy after login

However, browser security measures prevent sending the custom header values directly in the initial request. Instead, they are placed in the Access-Control-Request-Headers header. This is a security mechanism known as the preflighted request.

To allow the subsequent request to include the actual header values, the server must configure the necessary CORS (Cross-Origin Resource Sharing) headers.

A solution to this is sending the headers in a different way, as shown in the given sample code:

$.ajax({
  type: "POST",
  beforeSend: function(request) {
    request.setRequestHeader("Authority", authorizationToken);
  },
  url: "entities",
  data: "json=" + escape(JSON.stringify(createRequestObject)),
  processData: false,
  success: function(msg) {
    $("#results").append("The result =" + StringifyPretty(msg));
  }
});
Copy after login

This approach actually sets the request header values directly, bypassing the Access-Control-Request-Headers placement. It provides a way to send custom headers with the initial request without requiring server configuration.

The above is the detailed content of How to Send Custom Headers in AJAX POST Requests with jQuery?. 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