3

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

Weishi Z
  • 1,629
  • 5
  • 18
  • 38

2 Answers2

2

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

Weishi Z
  • 1,629
  • 5
  • 18
  • 38
1

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.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
  • I've set it to be origin domain. But localhost have this issue as well. (localhost requesting resources at other domain. ) – Weishi Z Jun 28 '16 at 02:01