kri*_*rak 16 ajax jquery curl basic-authentication
我正在尝试使用jquery ajax进行api调用,我已经为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
Run Code Online (Sandbox Code Playgroud)
我试过像这样的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");
}
});
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
kri*_*rak 31
默认情况下,$ .ajax()将转换data为查询字符串,如果还不是字符串,因为data这是一个对象,将其更改data为字符串然后设置processData: false,以便它不会转换为查询字符串.
$.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");
}
});
Run Code Online (Sandbox Code Playgroud)