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); });
Understandably, you would expect the headers to be sent as:
My-First-Header: first value My-Second-Header: second value
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)); } });
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3