5

I want to pass Authorization header while POSTing data to server. I tried

$.ajax({
   url : <ServiceURL>,
   data : JSON.stringify(JSonData),
   type : 'POST',
   contentType : "text/html",
   dataType : 'json',
   success : function(Result) {
   },
   beforeSend: function (xhr) {
      xhr.setRequestHeader('Authorization', <Authorization Header Value>);
   },
   error: function (RcvData, error) {
      console.log(RcvData);
   }
});

But REST service returns error (error code : 500). The same service was working fine with $.post() before adding authorization. could anyone tell me "How to pass authorization header in $.post()??"

Umesh Kadam
  • 843
  • 2
  • 7
  • 14

2 Answers2

4

Use

 contentType: 'application/json',

You may have gotten data and contentType mixed up.

  • contentType is the Content-type header you send.

  • data changes how jQuery treats the data you receive.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285
4

The jQuery $.ajax() method accepts a headers value in the settings object.

So:

$.ajax({
    // url, data, etc...
    headers: {
        "Authorization" :"Basic " + myBase64variable,
        "Content-Type" :"application/json"
    }
});

Source: http://api.jquery.com/jquery.ajax/

PS: Seems you can also pass in a new settings object in the beforeSend parameter. I didn't know this, so thanks for asking this question :)

Croot
  • 331
  • 1
  • 10