I am struggling for hours now. I want to make a simple ajax request to another domain, but get http 401 Error all the time:
jQuery(document).ready(function($
UPDATE Looks like I was not right. Authorization
header is never sent for OPTIONS
request. Please see comment by sideshowbarker - you need to make sure that your server doesn't respond with 401
to OPTIONS
request.
I don't know what language is your server written in, but you implemented authorization in the wrong way - OPTIONS method should be excluded from auth. Also see here - OPTIONS request authentication
Below is obsolete answer:
Your serverside requires HTTP Basic authentication for this request. And you don't provide credentials. 401 error has nothing to do with CORS; it just means that the server chose to not authorize your request because you didn't provide auth credentials.
If you try to open this url (like https://dev.radbonus.com/admin/affiliate-connections/retrieveSingle/1.json) directly in browser, you will be asked to enter login&password, which is how the browser handles 401 error with WWW-Authenticate
header.
Please notice that Authorization
header is actually not included with your request.
So instead of using beforeSend
hook, you should probably just include header directly in your call:
headers: {
'Authorization': 'Basic ' + btoa(username+':'+password),
},
And make sure that Authorization
header presents in your request.
You should check if you have disabled "Anonymous Authentication" in order to allow any authentication like "Windows Authentication". If you disabled it you will get 401 for any preflight request since they don't send credentials in their request.
You should enable "Anonymous Authentication" and use "Authorization Rules" section in IIS to avoid anonymous access. in case you don't have it, you can install it in windows features under the section:
Internet Information Services(IIS) - World Wide Web Services - Security - URL Authorization
You can for example set your authorization rules like this:
You can read more about it here
Please add cross domain in headers like this:
$.ajax({
url: "https://dev.radbonus.com/admin/affiliate-connections/retrieveSingle/"+challengeid+".json",
method: "GET",
dataType: "json",
jsonp: false,
contentType: "application/json",
xhrFields: {
withCredentials: true
},
crossDomain: true,
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Basic "+ btoa(username+":"+password));
xhr.setRequestHeader("Access-Control-Allow-Origin",'*');
},
success: function(data){
$('#codepressHock').html(data.data.code);
},
error: function(error){
alert(error);
}
});