我正在尝试使用jQuery的ajax方法进行API调用,我的curl命令可以正常使用该API,但是我的ajax会抛出HTTP 500错误。
这是我成功的curl命令:
curl -u "username:password" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"foo":"bar"}' http://www.example.com/api
我尝试了这样的ajax,但它不起作用:
$.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");
}
});
我错过了什么?