【问题标题】:CORS error in using XMLHttpRequest while using Axios avoid the issue使用 Axios 时使用 XMLHttpRequest 时出现 CORS 错误避免了该问题
【发布时间】:2022-02-02 21:55:51
【问题描述】:

我刚刚开始学习如何使用 Javascript 向 API 发出请求,并且我已经坚持了几个小时。

我使用了以下公共 API: http://www.penguinrandomhouse.biz/webservices/rest/

问题是,当我使用 XMLHttpRequest 时,我总是遇到错误。起初我没有在标题中包含内容类型,我得到了 404,当我包含它时,错误我得到了一个 CORS 错误。 以下是代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <title>Request book</title>
    <style>
    ...
    </style>
    
  </head>

  <body>
    <section class="preview">
      <div id="return_content"></div>
    </section>
    <script>
      let request = new XMLHttpRequest();
      const url = "https://reststop.randomhouse.com/resources/authors";
      request.open("GET", url);
      let content = {
        lastName : "Grisham",
      }
      request.setRequestHeader('Content-type', 'application/json');
      /* I did not add this at first, but it seems like the 
      default content type for XHR is not what the API wants*/
      request.send(JSON.stringify(content));
      request.onreadystatechange = () => {
        if (this.readyState == 4 && this.status == 200){
          console.log(request.responseText);
          /* let content_div = document.querySelector('#return_content');
          content_div.innerText = request.responseText; */
        }
      }
    </script>
  </body>
  
</html>

错误信息如下:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://reststop.randomhouse.com/resources/authors. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200

但我尝试先在 node.js 中使用 Axios 发送请求,如下所示,一切正常;所以我认为我的请求一定有问题。但是,据我了解,CORS 策略应该由服务器设置,并且从 this post 看来我无法设置 Access-Control-Allow-Origin - 它应该是服务器端提供的东西。

请求中似乎缺少某些内容,但我真的不知道。任何帮助或提示将不胜感激!

【问题讨论】:

    标签: api http xmlhttprequest preflight


    【解决方案1】:

    似乎我没有阅读所有文档……我一直在阅读有关 API 的内容,但没有详细阅读 CORS MDN 页面。 无论如何,我会把它留在这里,以防将来有人需要它。

    引用自 MDN: For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.

    我认为这意味着 CORS 策略也是浏览器保护自己免受恶意脚本攻击的一种方式,很可能是针对存储在浏览器中的 cookie 的脚本。

    我发现最令人困惑的是,错误消息在我在 header 中添加 content-type 之前和之后发生了变化。那里发生的事情是,我在不知情的情况下提出了一个“简单请求”(来自this post,默认内容类型是纯文本),这就是为什么它没有触发 CORS 策略而只给了我一个 404 .

    【讨论】:

      猜你喜欢
      • 2020-05-14
      • 2021-05-16
      • 1970-01-01
      • 2020-08-07
      • 2019-09-28
      • 2019-11-10
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多