Converting curl cmd to jQuery $.ajax()

后端 未结 1 498
借酒劲吻你
借酒劲吻你 2020-12-13 07:41

I\'m trying to make a api call with jquery ajax, I have curl working for the api, but my ajax is throwing HTTP 500

I have a curl command working that looks like this

相关标签:
1条回答
  • 2020-12-13 08:10

    By default $.ajax() will convert data to a query string, if not already a string, since data here is an object, change the data to a string and then set processData: false, so that it is not converted to 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");
        }
    });
    
    0 讨论(0)
提交回复
热议问题