I'm working on a consumer for a self-made API and having serious difficulties with setting the Authorization header. I am using JQuery for the Ajax requests, but the 'beforeSend' does not work at all (using fiddler to examine the requests)
This is my beforeSend code:
$.ajax({
type: "GET",
url: url+"/Projects",
contentType: "application/json; charset=utf-8",
beforeSend: function (req) {
req.setRequestHeader("Authorization", AuthBuilder(username, password));
},
success: function (result) {
alert("success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("fail");
}
});
Well if that fails what do you do? Go back to the old way for sending ajax requests... well this doesn't work either...
This is my regular code:
function GET(address, callback, error) {
Request = getXMLHttpObject();
Request.open("GET", url + address, true);
var base64 = Base64.encode(username + ":" + password);
alert(base64);
Request.setRequestHeader("Authorization", "Basic " + base64);
Request.send();
Request.onreadystatechange = function () {
//alert(Request.readyState+" code "+Request.status);
if (Request.readyState == 4 && Request.status == 200) {
callback(jQuery.parseJSON(Request.responseText));
} else if (Request.readyState == 4 && Request.status >= 400) {
error(Request.status, Request.statusText);
}
}
}
Don't mind the fact that I'm not asking for json specifically because the service returns json by default.
In additional info:
- the origin does not matter, the service allows all origins (has been tested and confirmed)
- the Authorization works when set by headers (tested in other clients)
- the Authorization headers just aren't sent
- AuthBuilder(username, password)) gives the correct format of the Basic Auth header content
- the getXMLHttpObject() is just some copy paste code and worked before
any thoughts ?