我尝试使用 ajax (xmlHttpRequest) 使用 WCF 服务 (REST)。该服务需要基本身份验证。
我的ajax调用是:
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
//do some stuff
}
}
};
httpRequest.open('PUT', 'http://localhost:59000/v1/users/1', true, 'user1', 'user1');
httpRequest.withCredentials = "true";
//must authenticate both..in open() but also set header manually ...cf http://stackoverflow.com/questions/1358550/xmlhttp-request-basic-authentication-issue
httpRequest.setRequestHeader('Auhtorization', 'Basic user1:user1');
httpRequest.setRequestHeader('Accept', 'application/json');
// overridemimeType() does not set content type header .... don't know why ?
httpRequest.setRequestHeader('Content-Type', 'application/json');
var params = { "UserName": "user1" };
var requestBodyString = JSON.stringify(params);
httpRequest.send(requestBodyString);
我首先在服务器端处理请求的方式如下
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin",
crossDomain);
//preflight request : cf https://developer.mozilla.org/en/http_access_control
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, DummyOneForTest");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
"1728000");
HttpContext.Current.Response.End();
}
我的浏览器向我发送错误“请求标头字段授权不受 Access-Control-Allow-Headers 的允许”,但您可以看到它在响应标头中。
此外,当我尝试使用 Fiddler 时,一切都很好,我什至允许标题虚拟一个。
所以我真的很困惑,如果有人可以帮忙,请做!
谢谢