我遇到一个神秘的问题,Chrome在遇到HTTP重定向时会取消跨源AJAX请求。在“网络”选项卡中,它显示为“(已取消)”,并且响应标题或正文不可用。
这是流程:
这是JS(来自ajaxtest.html
):
var r = new XMLHttpRequest();
r.open('POST', 'https://dev.example.com/appName-rest/login', true);
r.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
r.send(JSON.stringify({"username":"myusername","password":"myrealpassword"}));
r.send();
Chrome的网络内部显示服务器响应了这些标头:
HTTP/1.1 303 See Other
Date: Thu, 05 Sep 2013 17:54:21 GMT
Server: Apache/2
Access-Control-Allow-Origin: http://dev.example.com
Access-Control-Allow-Credentials: true
Location: https://dev.example.com/appName-rest/j_spring_cas_security_check?ticket=xxxx.example.com
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
Content-Length: 52
Connection: close
Content-Type: text/plain; charset=UTF-8
它说:URL_REQUEST_BLOCKED_ON_DELEGATE
有谁知道为什么会失败?
答案 0 :(得分:3)
似乎你正在尝试Cross-Origin Request with Preflight,因为你设置'Content-Type':'application / json'。带有重定向的预检请求会被CORS specs拒绝。
答案 1 :(得分:0)
您正在发送两次此方法:r.send();
请尝试以下
var xhr = new XMLHttpRequest();
xhr.open("POST", "YOUR_URL", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function (event) {
if (xhr.readyState === 4 && xhr.status === 200) { // if complete and success
return xhr.responseText;
}
};
xhr.withCredentials = true; // OPTIONAL : I don't know if you need it for CORS Requests
xhr.send("username=YOUR_USERNAME&password=YOUR_PASSWORD");