Javascript CORS - No 'Access-Control-Allow-Ori

2019-01-28 18:56发布

I've been working with CORS and encountered the following issue. Client complains about no 'Access-Control-Allow-Origin' header is present, while they are present, and client make the actual POST request and receives 200.

function initializeXMLHttpRequest(url) {  //the code that initialize the xhr
    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.withCredentials = true;
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

    //set headers
    for (var key in headers) {
        if (headers.hasOwnProperty(key)) {  //filter out inherited properties
            xhr.setRequestHeader(key,headers[key]);
        }
    }

        return xhr;
}

enter image description here

In Chrome

chrome console log

chrome console log

Chrome OPTIONS request chrome options

Chrome POST request chrome post

In Firefox

Firefox Console Log firefox console log

Firefox OPTIONS request firefox options

Firefox POST request firefox post

2条回答
狗以群分
2楼-- · 2019-01-28 19:13

In short: Access control headers (e.g. Access-Control-Allow-Origin) need to present in response for both OPTIONS and actual POST.

Work Flow:

  1. Client make OPTIONS request with those HTTP access headers. (e.g. Origin, Access-Control-Request-Method, Access-Control-Request-Headers)

  2. Server respond with those access control headers, allowing access. (e.g. Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Allow-Credentials, Access-Control-Allow-Methods, Access-Control-Allow-Headers)

  3. Client makes POST request with data.

  4. Server respond to POST. If Access-Control-Allow-Origin header is NOT present in the server response. Although the POST is successful and shows 200 status code in network tab, xhr.status is 0 and xhr.onerror will be triggered. And browser would show up the error message.

Header References: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

查看更多
地球回转人心会变
3楼-- · 2019-01-28 19:23

Value null for Access-Control-Allow-Origin won't do, it has to be either the origin domain or * to allow any origin.

For more details, refer to MDN.

查看更多
登录 后发表回答