Add header in AJAX request with jQuery

Add header in AJAX request with jQuery

I would like to add a custom header to an AJAX POST request from jQuery.
I have tried this:
type: ‘POST’,
url: url,
headers: {
“My-First-Header”:”first value”,
“My-Second-Header”:”second value”
//beforeSend: function(xhr) {
// xhr.setRequestHeader(“My-First-Header”, “first value”);
// xhr.setRequestHeader(“My-Second-Header”, “second value”);
}).done(function(data) {

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

OPTIONS xxxx/yyyy HTTP/1.1
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 1:

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:

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.

Solution 2:

Here is an example how to set a Request Header in a JQuery Ajax Call:

  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));

Solution 3:

This code below works for me. I always use only single quotes, and it works fine. I suggest you should use only single quotes OR only double quotes, but not mixed up.

    url: 'YourRestEndPoint',
    headers: {
        'Authorization':'Basic xxxxxxxxxxxxx',
    method: 'POST',
    dataType: 'json',
    data: YourData,
    success: function(data){
      console.log('succes: '+data);

Hope this answers your question…

Solution 4:

Because you send custom headers so you CORS request is NOT SIMPLE REQUEST so browser first send prefilight OPTIONS request to check that server allow your request.

enter image description here

If you turn on CORS on the server then your code will works. You can also use js fetch instead (here)

let url=',My-Second-Header';

    type: 'POST',
    url: url,
    headers: {
        "My-First-Header":"first value",
        "My-Second-Header":"second value"
}).done(function(data) { 
    alert(data[0].request.httpMethod + ' was send - open chrome console> network to see it');
<script src=""></script>

Here is example configuration which turn on CORS on nginx (nginx.conf file)

location ~ ^/index\.php(/|$) {
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    if ($request_method = OPTIONS) {
        add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';
        add_header 'Content-Length' 0;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        return 204;

Here is example configuration which turn on CORS on apache (.htaccess file)

# ------------------------------------------------------------------------------
# | Cross-domain AJAX requests                                                 |
# ------------------------------------------------------------------------------

# Enable cross-origin AJAX requests.

# <IfModule mod_headers.c>
#    Header set Access-Control-Allow-Origin "*"
# </IfModule>

#Header set Access-Control-Allow-Origin ""
#Header always set Access-Control-Allow-Credentials "true"

Header set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"

Solution 5:

And that is why you can’t create a bot with Javascript, because your options are limited to what the browser allows you to do. You can’t just order a browser that follows the CORS policy, which most browsers follow, to send random requests to other origins and allow you to get the response that simply!

Additionally, if you tried to edit some request headers manually like origin-header from the developers tools that come with the browsers, the browser will refuse your edit, and may send a preflight OPTIONS request.

Solution 6:

Try to use rack-cors gem. And add the header field in your ajax call.