0

In one of my code I've the following jQuery AJAX call

$.ajax({
    url: "https://api.myapi.com/v1/post/",
    type: "POST",
    dataType: "json",
    data: JSON.stringify(body),
    success: function (data, status, xhr)
    {
        console.log(xhr.getAllResponseHeaders()); // Output-01
        console.log(xhr.getResponseHeader('Authorization')); // Output-02
    },
    error: function (data) {
        //console.log(data);
    }
})

I have got the following output:

  • Output-01: content-type: application/json
  • Output-02: null

I can't figure out what did I do wrong?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Siddiqui Noor
  • 5,575
  • 5
  • 25
  • 41
  • 1
    Try checking your browsers developer console `` to ensure the header is being returned as you expect. – War10ck May 23 '18 at 15:09
  • 2
    An `Authorization` header in the *response*? Are you sure that's correct. The norm, by far, is to only send the Auth headers in the request in order to identify exactly *who* is requesting the resource. – Rory McCrossan May 23 '18 at 15:12
  • @RoryMcCrossan yes, that's correct. – Siddiqui Noor May 23 '18 at 15:16
  • 1
    If it's your API then you're defining what's sent back. As Rory said, however, it'd be an odd thing to send that *back*, e.g., https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization You only have access to the headers actually sent. – Dave Newton May 23 '18 at 15:17
  • @War10ck I see my Network tab is showing all the available headers like `content-type`, `authorization`, `statusCode` and so on. – Siddiqui Noor May 23 '18 at 15:17
  • `Authorization` != `authorization`, and it may also be affected by any jQuery default ajax handling in play or whatever else jQuery may do to XHR requests. – Dave Newton May 23 '18 at 15:20
  • @Taplar `authorization` is also not worked. You see my `console.log(xhr.getAllResponseHeaders());` returns only `content-type: application/json` and there is no other header is accessible from my JS code :( – Siddiqui Noor May 23 '18 at 15:21
  • @Taplar you are absolutely right. I am performing a cross site request. and your suggestion works perfect. – Siddiqui Noor May 23 '18 at 15:49
  • Alright, then I'll vote to close as a duplicate. Glad you got it figured out though. – Taplar May 23 '18 at 15:51

0 Answers0