问题
I'm having a mysterious issue where Chrome cancels cross-origin AJAX requests when they encounter a HTTP redirect. In the Network tab, it appears as "(canceled)" and the response headers or body are not available.
Here's the flow:
- Load page on http://
- POST request to login endpoint on https://
- 303 response
- Request canceled.
Here's the JS (from 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's net internals shows that the server responded with these headers:
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
And it says: URL_REQUEST_BLOCKED_ON_DELEGATE
Does anyone know why this is failing?
回答1:
Seems you are trying to do Cross-Origin Request with Preflight, because you setup 'Content-Type': 'application/json'. Preflighted requests with redirects are rejected by CORS specs.
回答2:
You are sending twice this method : r.send();
Please, try the following
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");
来源:https://stackoverflow.com/questions/18643260/chrome-cancels-cors-xhr-when-redirected