我正在使用以下内容发出CORS请求:
// This causes a problem....
$.support.cors = true;
$.ajax({
url: url,
type: 'GET',
data: {},
dataType: 'json',
contentType: "application/json; charset=utf-8",
crossDomain: true,
success: function (result, textStatus, jqXHR) {
alert('Success');
},
error: function (jqXHR, textStatus, err) {
var problem = jqXHR.responseText;
if (problem == undefined) {
problem = err;
}
if (window.console) console.log("Error with ajax call: " + problem);
},
beforeSend: function (xhr) {
var headerValue = "Basic <base64 user name and password>";
xhr.setRequestHeader('Authorization', headerValue);
}
});
并且Fiddler请求是:
GET http://api.scenictours.com/api/Guests?query=firstName::|surname::Testcustomer|dateOfBirth::|gender::|postcode::|email::|phone::|clientmarket::AU HTTP/1.1
Accept: */*
Origin: http://localhost:50485
Accept-Language: en-AU,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Host: api.scenictours.com
DNT: 1
Connection: Keep-Alive
Pragma: no-cache
任何人都可以告诉我为什么认证标题消失了吗?
答案 0 :(得分:0)
看一下这个问题的答案 - Basic authentication using XHR
显然,对于跨域请求,存在一些授权标头错误。
答案 1 :(得分:0)
根据https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS#Requests_with_credentials
默认情况下,在跨站点XMLHttpRequest调用中,浏览器不会发送凭据。调用XMLHttpRequest对象时,必须在其上设置一个特定的标志。
因此,您需要再向beforeSend
添加一行:
xhr.withCredentials = true;