Bob
Bob

Reputation: 3084

Jquery Ajax not sending headers

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.

Upvotes: 6

Views: 13553

Answers (2)

Roberto Andrade
Roberto Andrade

Reputation: 1853

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.

Upvotes: 2

Undefitied
Undefitied

Reputation: 747

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"
    }
})

Upvotes: 6

Related Questions