我现在挣扎了好几个小时.我想向另一个域发出一个简单的ajax请求,但始终获取http 401错误:
jQuery(document).ready(function($){
var challengeid = $('#codepressHook').data('challengeid');
var clicked = false;
$('#codepressHook').click(function(){
if(!clicked){
$.ajax({
url: "https://dev.radbonus.com/admin/affiliate-connections/retrieveSingle/"+challengeid+".json",
method: "GET",
dataType: "json",
jsonp: false,
contentType: "application/json",
xhrFields: {
withCredentials: true
},
beforeSend: function(xhr){
xhr.setRequestHeader("Authorization", "Basic "+ btoa(username+":"+password));
},
success: function(data){
$('#codepressHock').html(data.data.code);
},
error: function(error){
alert(error);
}
});
}
});
});
我在服务器端设置了所有相关的CORS头.这是网络流量:
Request URL:https://dev.radbonus.com/admin/affiliate-connections/retrieveSingle/45.json
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:185.102.94.230:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, X-Requested-With, Authorization, Origin
Access-Control-Allow-Methods:POST, GET, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:http://radbonus.com
Access-Control-Max-Age:31536000
Content-Length:463
Content-Type:text/html; charset=iso-8859-1
Date:Sat, 24 Jun 2017 11:25:33 GMT
Server:Apache/2.4.18 (Ubuntu)
WWW-Authenticate:Basic realm="Admin"
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:authorization,content-type
Access-Control-Request-Method:GET
Connection:keep-alive
Host:dev.radbonus.com
Origin:http://radbonus.com
Referer:http://radbonus.com/plugintest/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
我知道这个主题有很多帖子,但似乎我错过了一些简单的东西.谁能帮助我?
解决方法:
更新看起来我不对.永远不会为OPTIONS请求发送授权标头.请参阅comment by sideshowbarker
– 您需要确保您的服务器没有响应401到OPTIONS请求.
我不知道您的服务器是用什么语言编写的,但是您以错误的方式实现了授权 – 应该从auth中排除OPTIONS方法.另见 – OPTIONS request authentication
以下是过时的答案:
您的服务器端要求此请求的HTTP基本身份验证.而且您不提供凭据. 401错误与CORS无关;它只是意味着服务器选择不授权您的请求,因为您没有提供身份验证凭据.
如果您尝试直接在浏览器中打开此URL(如https://dev.radbonus.com/admin/affiliate-connections/retrieveSingle/1.json),则会要求您输入login& password,这是浏览器使用WWW-Authenticate标头处理401错误的方式.
请注意,您的请求实际上不包含授权标头.
因此,您可能只需在调用中直接包含标题,而不是使用beforeSend挂钩:
headers: {
'Authorization': 'Basic ' + btoa(username+':'+password),
},
并确保在您的请求中显示Authorization标头.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。