Chrome cancels CORS XHR when redirected

試著忘記壹切 提交于 2021-01-28 01:52:41

问题


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:

  1. Load page on http://
  2. POST request to login endpoint on https://
  3. 303 response
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!