Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass authorization header in $.post() method using Javascript?

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()??"

like image 812
Umesh Kadam Avatar asked Jan 22 '14 06:01

Umesh Kadam


People also ask

How can I send authorization in post request?

To send a POST JSON request with a Bearer Token authorization header, you need to make an HTTP POST request, provide your Bearer Token with an Authorization: Bearer {token} HTTP header and give the JSON data in the body of the POST message.

How do I pass the authorization header in GET request?

To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.

How do I authorize my header?

The command requires the valid user name and password (or API token) in the application to which you want to connect, and it encodes the credentials with base64. In the Authorization Header field, you enter the word "Basic" (which is the Authorization header type), a space, and then the base64-encoded credentials.

How do I send a header token?

To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.


2 Answers

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.

like image 55
Paul Draper Avatar answered Oct 10 '22 23:10

Paul Draper


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 :)

like image 4
Croot Avatar answered Oct 11 '22 01:10

Croot