lan*_*sen 4 javascript ajax http-error cors
我现在挣扎了好几个小时.我想向另一个域发出一个简单的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);
}
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
我在服务器端设置了所有相关的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
Run Code Online (Sandbox Code Playgroud)
我知道这个主题有很多帖子,但似乎我错过了一些简单的东西.谁能帮助我?
Mar*_*oft 12
更新看起来我不对.Authorization
标头永远不会发送OPTIONS
请求.请参阅的评论sideshowbarker
-你需要确保你的服务器不响应401
到OPTIONS
请求.
我不知道您的服务器是用什么语言编写的,但是您以错误的方式实现了授权 - 应该从auth中排除OPTIONS方法.另请参见此处 - OPTIONS请求身份验证
以下是过时的答案:
您的服务器端要求此请求的HTTP基本身份验证.而且您不提供凭据.401错误与CORS无关; 它只是意味着服务器选择不授权您的请求,因为您没有提供身份验证凭据.
如果您尝试直接在浏览器中打开此URL(如https://dev.radbonus.com/admin/affiliate-connections/retrieveSingle/1.json),系统将要求您输入登录名和密码,这是浏览器处理401的方式WWW-Authenticate
标题错误.
请注意,Authorization
标题实际上不包含在您的请求中.因此beforeSend
,您可能只需在调用中直接包含标题,而不是使用hook:
headers: {
'Authorization': 'Basic ' + btoa(username+':'+password),
},
Run Code Online (Sandbox Code Playgroud)
并确保Authorization
标头出现在您的请求中.
归档时间: |
|
查看次数: |
18516 次 |
最近记录: |