Skip to content
Fix Code Error

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

March 13, 2021 by Code Error
Posted By: Anonymous

I would like to add a custom header to an AJAX POST request from jQuery.

I have tried this:

$.ajax({
    type: 'POST',
    url: url,
    headers: {
        "My-First-Header":"first value",
        "My-Second-Header":"second value"
    }
    //OR
    //beforeSend: function(xhr) { 
    //  xhr.setRequestHeader("My-First-Header", "first value"); 
    //  xhr.setRequestHeader("My-Second-Header", "second value"); 
    //}
}).done(function(data) { 
    alert(data);
});

When I send this request and I watch with FireBug, I see this header:

OPTIONS ✘✘✘x/yyyy HTTP/1.1
Host: 127.0.0.1:6666
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Origin: null
Access-Control-Request-Method: POST
Access-Control-Request-Headers: my-first-header,my-second-header
Pragma: no-cache
Cache-Control: no-cache

Why do my custom headers go to Access-Control-Request-Headers:

Access-Control-Request-Headers: my-first-header,my-second-header

I was expecting a header values like this:

My-First-Header: first value
My-Second-Header: second value

Is it possible?

Solution

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.

Answered By: Anonymous

Related Articles

  • Error using core-scaffold from polymer JS in the latest…
  • How are zlib, gzip and zip related? What do they have in…
  • CORS GET returns an empty response body in Firefox
  • How to get a cross-origin resource sharing (CORS) post…
  • Is CSS Turing complete?
  • What is the worst programming language you ever worked with?
  • How do we control web page caching, across all browsers?
  • Issue adding access token to header in Backbone: It changes…
  • Python send POST with header
  • vue-resource Headers from the cross-origin response is not…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Check whether a string matches a regex in JS

Next Post:

How do I center floated elements?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error