6

I've read countless answers regarding similar questions, but cannot solve my specific issue.

I have a web API that makes a request to RESTful service using a oauth token. This is cross domain.

I know my cors is setup correctly as I can make requests from the app without issue.

My problem is that my headers are not being sent.

$.ajax({
        type: "GET",
        crossDomain: true,
        url: url,
        data: data,
        success: success,
        dataType: 'json',
        cache: false,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "bearer TOKENGOESHERE"),
            xhr.setRequestHeader("RandomHeader", "test")
        }
    });

If I call my API using fiddler and set the header there, the API gets the header as expected. It's only this AJAX call that doesn't seem to work.

I am running this in the latest Chrome browser.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Bob
  • 3,074
  • 11
  • 43
  • 62

2 Answers2

6

Have you tried to send headers as a parameter?

$.ajax({
    type: 'POST',
    url: url,
    headers: {
        "my-first-header": "first value",
        "my-second-header": "second value"
    }
})
Undefitied
  • 747
  • 5
  • 14
  • 1
    $.ajax({ type: "GET", crossDomain: true, url: url, data: data, success: success, dataType: 'json', cache: false, headers:{ "Authorization" : "bearer TOKENGOESHERE", "RandomHeader": "test" } }); – Bob Mar 20 '16 at 14:09
  • 2
    I've realized my mistake, and it's a stupid one. I was setting my ajax call correctly all along (also headers as parameters works). My problem was that I was using the incorrect ajax class (helper) in my app. – Bob Mar 20 '16 at 14:22
  • 5
    @Byron could you ellaborate, please? I have the same problem and cannot see what I'm doing wrong. – Pere Mar 07 '17 at 15:37
  • I am doing that but if I do it from a SharePoint subsite (`http://mysite/mysite`), it doesn't send headers but from the SharePoint main site (`http://mysite`) it sends fine. – Si8 Mar 31 '17 at 14:21
  • 3
    @Bob what do you mean by helper? I'm using `$.ajax({})` and my headers are being stripped as well – Tom Bird Nov 14 '17 at 22:05
2

I had similar symptoms but my specific problem seemed to be I was making an http request to a site that enforced HTTPS, so when the browser got the 301 response pointing to the secure version of the site, it seems like the XHR subsystem follows the redirect but drops the headers in the process.

Roberto Andrade
  • 1,793
  • 1
  • 21
  • 27