Convert curl cmd to jQuery $ .ajax ()

I am trying to make an api call with jquery ajax, I have curl running on api, but my ajax throws HTTP 500

I have a curl command that looks like this:

curl -u "username:password" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"foo":"bar"}' http://www.example.com/api 

I tried ajax like this, but it does not work:

 $.ajax({ url: "http://www.example.com/api", beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); }, type: 'POST', dataType: 'json', contentType: 'application/json', data: {foo:"bar"}, success: function (data) { alert(JSON.stringify(data)); }, error: function(){ alert("Cannot get data"); } }); 

What am I missing?

+8
jquery ajax curl basic-authentication
source share
1 answer

By default, $ .ajax () converts data into a query string, if not already a string, since data is an object here, change data to a string, and then set processData: false so that it does not convert to a query string.

 $.ajax({ url: "http://www.example.com/api", beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); }, type: 'POST', dataType: 'json', contentType: 'application/json', processData: false, data: '{"foo":"bar"}', success: function (data) { alert(JSON.stringify(data)); }, error: function(){ alert("Cannot get data"); } }); 
+18
source share

All Articles