Javascript jQuery ajax和跨域(CORS)以及基本身份验证
我尝试了建议的可能重复问题中的答案,但结果没有改变 我一直试图通过ajax从本地PC上的客户端(测试Chrome和IE)发布到远程服务器的API,但没有成功。 Ajax返回一个状态为0的错误,服务器返回401。 在没有基本身份验证的情况下,我确认它是有效的。但对于基本身份验证,它从未起作用 客户:Javascript jQuery ajax和跨域(CORS)以及基本身份验证,javascript,jquery,ajax,apache,cross-domain,Javascript,Jquery,Ajax,Apache,Cross Domain,我尝试了建议的可能重复问题中的答案,但结果没有改变 我一直试图通过ajax从本地PC上的客户端(测试Chrome和IE)发布到远程服务器的API,但没有成功。 Ajax返回一个状态为0的错误,服务器返回401。 在没有基本身份验证的情况下,我确认它是有效的。但对于基本身份验证,它从未起作用 客户: $.ajax({ type : 'POST', url : 'http://api-url', data : data, success : function (res
$.ajax({
type : 'POST',
url : 'http://api-url',
data : data,
success : function (response) {
console.log(response);
},
error : function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
},
beforeSend : function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic base64username:password');
},
xhrFields : {
withCredentials : true
}
服务器:
<?php
header('Access-Control-Allow-Origin: http://localhost');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
echo "ok";
如果访问控制允许源的远程服务器设置仅设置为localhost,则它将仅适用于本地请求。
尝试:
可能重复的您是否使用base64对整个username:password
字符串进行了编码,还是仅对用户名进行了编码?我尝试了建议的可能重复问题中的答案,但没有更改结果。是的,我正确地对username:password进行了编码。我想我已经尝试过了(但没有成功),但我将稍后再试。
header('Access-Control-Allow-Origin:*);