Javascript CORS - No 'Access-Control-Allow-Origin' header is present

空扰寡人 提交于 2019-12-18 07:12:54

问题


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;
}

In Chrome

chrome console log

Chrome OPTIONS request

Chrome POST request

In Firefox

Firefox Console Log

Firefox OPTIONS request

Firefox POST request


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/38065756/javascript-cors-no-access-control-allow-origin-header-is-present

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