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.

3
  • did you try headers: {"header": "value"} property instead of beforeSend? Commented Mar 20, 2016 at 13:40
  • Have you confirmed this by inspecting the actual request in dev tools network tab? Commented Mar 20, 2016 at 13:48
  • 1
    @charlietfl I did indeed. Commented Mar 20, 2016 at 14:04

2 Answers 2

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"
    }
})
Sign up to request clarification or add additional context in comments.

5 Comments

$.ajax({ type: "GET", crossDomain: true, url: url, data: data, success: success, dataType: 'json', cache: false, headers:{ "Authorization" : "bearer TOKENGOESHERE", "RandomHeader": "test" } });
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.
@Byron could you ellaborate, please? I have the same problem and cannot see what I'm doing wrong.
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.
@Bob what do you mean by helper? I'm using $.ajax({}) and my headers are being stripped as well
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.