Access Control Request Headers, Is Added to Header in Ajax Request with Jquery

Access Control Request Headers, is added to header in AJAX request with jQuery

What you saw in Firefox was not the actual request; note that the HTTP method is OPTIONS, not POST. It was actually the 'pre-flight' request that the browser makes to determine whether a cross-domain AJAX request should be allowed:

http://www.w3.org/TR/cors/

The Access-Control-Request-Headers header in the pre-flight request includes the list of headers in the actual request. The server is then expected to report back whether these headers are supported in this context or not, before the browser submits the actual request.

How to add header to request in Jquery Ajax?

There are couple of solutions depending on what you want to do

If want to add a custom header (or set of headers) to an individual request then just add the headers property and this will help you to send your request with headers.

// Request with custom header
$.ajax({
url: 'foo/bar',
headers: { 'x-my-custom-header': 'some value' }
});

If want to add a default header (or set of headers) to every request then use $.ajaxSetup(): this will help you to add headers.

//Setup headers here and than call ajax
$.ajaxSetup({
headers: { 'x-my-custom-header': 'some value' }
});

// Sends your ajax
$.ajax({ url: 'foo/bar' });

add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

//Hook your headers here and set it with before send function.
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});

// Sends your ajax
$.ajax({ url: 'foo/bar' });

Reference Link : AjaxSetup

Reference Link : AjaxHeaders

Allow headers in cross-domain ajax request

It seems that each header must explicitly be listed and I added x-test-header to Access-Control-Allow-Headers.

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "x-test-header, Origin, X-Requested-With, Content-Type, Accept"

CORS ajax call fails despite of the appropriate Access-Control-Allow-* headers

The solution was not related to CORS at all, but the website (SalesForce) hosting my JS script.

Indeed SalesForce reloads the page after every ajax call. Chrome detects that the DOM node that triggered the ajax call is gone, so it judiciously cancels the request.

My solution was to make my ajax call synchronous.

Thanks @Quentin and @sideshowbarker for the ideas



Related Topics



Leave a reply



Submit