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

标签 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

最佳答案

当您未指定Content-type 时,XHR 会执行CORS 预检请求。请注意,您的请求是 OPTIONS,而不是 GET。这就是为什么您没有从网络选项卡中得到任何响应的原因。

根据 CORS specification :

A header is said to be a simple header if the header field name is an ASCII case-insensitive match for Accept, Accept-Language, or Content-Language or if it is an ASCII case-insensitive match for Content-Type and the header field value media type (excluding parameters) is an ASCII case-insensitive match for application/x-www-form-urlencoded, multipart/form-data, or text/plain.

(...)

It gets slightly more complicated if the resource author wants to be able to handle cross-origin requests using methods other than simple methods. In that case the author needs to reply to a preflight request that uses the OPTIONS method and then needs to handle the actual request that uses the desired method (DELETE in this example) and give an appropriate response.

因此,总而言之,如果您的 Content-Type 不同于 application/x-www-form-urlencodedmultipart/form-data text/plain,XHR 将触发预检(发送一个OPTIONS http 动词)。

关于javascript - 为什么 CORS 在不同的内容类型下给出不同的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41928714/

相关文章:

javascript - 使用我从未在 JQuery 中定义的对象

java - 即使所有 CORS header 都存在,跨源资源共享问题

javascript - XMLHttpRequest 获取旧值

javascript - xhr 超时在 ie11 中给出无效状态错误

javascript - Google CDN 上的跨域请求

javascript - 修改 MongoDB 以允许跨源请求

javascript - 具有事件操作排除的事件监听

javascript - .html() jQuery 函数返回 NaN

javascript - dotVVM 将值从数据绑定(bind)的 DOM 元素传递到 JavaScript 变量以进行可视化

javascript - XMLHttpRequest HTTP header