为什么CORS在不同的内容类型中给出不同的响应

时间:2017-01-30 03:41:51

标签: javascript xmlhttprequest cors content-type

在没有请求内容类型的情况下调用第三方域的服务器时,我收到CORS错误而没有响应。但是当使用内容类型text / plain(这是响应的真实内容类型)进行调用时,我得到一个响应但是有一个CORS错误,所以我无法将其解析为dom。问题是为什么回应是第二次而不是第一次。两者仍然是CORS错误。如何从服务器获得响应后第二次解析错误?

   <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script>
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://www.w3schools.com/xml/ajax_info.txt', true);
        xhr.setRequestHeader('content-type', undefined);
        xhr.onload = function () {
            console.log('Test');
        };
        xhr.send(null);
        var contentXHR = new XMLHttpRequest();
        contentXHR.open('GET', 'http://www.w3schools.com/xml/ajax_info.txt', true);
        contentXHR.setRequestHeader('content-type', 'text/plain');
        contentXHR.onload = function () {
            console.log('Test request header');
        };
        contentXHR.send(null);
    </script>
  </head>
    <body>
            Check console and network tab
    </body>
</html>

enter image description here

enter image description here

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

如果您未指定CORS preflight request,则XHR会执行OPTIONS。请注意,您的请求是GET,而不是application/x-www-form-urlencoded。这就是您没有从网络标签中获得任何回复的原因。

根据CORS specification

  

如果标题字段名称是标题,则称标题为简单标题   Accept,Accept-Language或的ASCII不区分大小写的匹配项   内容 - 语言或如果它是ASCII不区分大小写的匹配   Content-Type和标题字段值媒体类型(不包括   参数)是ASCII的不区分大小写的匹配   application / x-www-form-urlencoded,multipart / form-data或text / plain。

     

(...)

     

如果资源作者希望如此,它会变得稍微复杂一些   能够使用除之外的方法来处理跨源请求   方法即可。在这种情况下,作者需要回复预检请求   使用OPTIONS方法,然后需要处理实际   请求使用所需的方法(在此示例中为DELETE)并给出   适当的回应。

因此,总而言之,如果您的内容类型与multipart/form-datatext/plainOPTIONS不同,XHR将触发预检(发送gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return 1; } }); recyclerView.setLayoutManager(gridLayoutManager); http动词)。