And*_*y T 9 jquery xmlhttprequest
需要使用javascript(在www.domain1.com)中使用Basic Auth进行REST GET调用.REST API位于domain2.com中.REST API返回CORS特定的HTTP标头.我需要支持IE,Chrome和Firefox.JavaScript下面进一步解释了这个问题 -
没有Basic Auth(IE 10中的WORKS,Chrome和Firefox,通过XDomainRequest对象处理旧的IE)
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
Run Code Online (Sandbox Code Playgroud)使用Basic Auth(仅限IE 10中的WORKS,Chrome和Firefox中的失败)
var xhr = new XMLHttpRequest();
xhr.open(method, url, true, username, password);
Run Code Online (Sandbox Code Playgroud)使用Basic Auth(在Chrome和Firefox中失败)
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
xhr. withCredentials = “true”;
Run Code Online (Sandbox Code Playgroud)使用Basic Auth(在Chrome和Firefox中失败)
$.ajax({
type: 'GET',
url: jsonp_url,
dataType: "json",
username: username,
password: pwd,
beforeSend: function (xhr) {xhr.withCredentials = true; },
success: function (result) { },
error: function (xhr, ajaxOptions, thrownError) {
}
Run Code Online (Sandbox Code Playgroud)
我很想在这里获得一个适用于Chrome和FireFox的基本身份验证的解决方案
它得到了解决.注意到浏览器使用身份验证通过两个步骤进行跨域调用 - 在实际请求之前进行预检调用.此预检调用的性质在IE和[Chrome + Firefox]中有所不同.IE进行HTTP GET预检调用,然后返回401,然后在实际请求中发送身份验证详细信息.但是,Chrome和Firefox采用更加安全的方法,通过进行HTTP OPTIONS调用来检查Web服务器支持的所有内容为CORS(允许哪些域/是否支持GET/POST等),并且下一次调用与实际的HTTP GET请求相关用身份验证.
不幸的是,API方面的编码方式是它正在验证每个Http调用.这就是为什么即使HTTP OPTIONS调用也回来了401. [chrome + Firefox]在预检调用之后正在抛出异常.
在API方面,修改了代码,以便在OPTIONS调用的情况下不返回401并且它开始工作.