【问题标题】:Why does CORS block my Http request when sent from the browser but not from the terminal为什么CORS从浏览器发送而不是从终端发送时会阻止我的Http请求
【发布时间】:2021-07-23 14:32:08
【问题描述】:

我对 CORS 提供的安全性有点困惑。下面是两个几乎相同的 HTTP 请求,一个有效,一个无效,一个是通过 curl 另一个是浏览器中的 javascript。

终端

$ curl https://www.google.com/
--> Returns a page

浏览器:

// Open the console in the browser (or spin put localhost)
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.google.com");
xhr.send();
--> CORS Error

再试一次:

  const xhr = new XMLHttpRequest();
  xhr.open("GET", "https://www.google.com");
  xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
  xhr.setRequestHeader("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
  xhr.setRequestHeader("Access-Control-Allow-Headers", 'Origin,Authorization,Content-Type,X-Auth-Token');
  xhr.setRequestHeader("Access-Control-Allow-Credentials", 'true') 
  
  xhr.send();
--> CORS Error still

所以我猜测 google.com 服务器已将其设置为仅接受来自 google 域的请求。但是,当我从不属于谷歌域的终端卷曲时,我会收到带有 HTML 等的 200 响应。

那么为什么服务器会响应我没有域的终端,而当我在浏览器中使用javascript时没有响应?

谢谢^.^

【问题讨论】:

标签: javascript networking xmlhttprequest cors network-security


【解决方案1】:

CORS 是浏览器提供的一项功能。 CORS 是一种机制,旨在允许代表您发出请求,同时阻止流氓 JS 发出的某些请求,并且在您向以下位置发出 HTTP 请求时触发:

  1. 不同的域(例如,example.com 上的站点调用 api.com)
  2. 不同的子域(例如,example.com 上的站点调用 api.example.com)
  3. 不同的端口(例如,example.com 上的站点调用 example.com:3001)
  4. 不同的协议(例如,https://example.com 的站点调用 http://example.com

请查看附件-https://medium.com/@baphemot/understanding-cors-18ad6b478e2b

【讨论】:

    【解决方案2】:

    CORS 是最终由您的浏览器实现的安全功能。这就是为什么您在从终端卷曲时永远不会看到 CORS 错误的原因。另见:this post from mozilla

    上面写着:

    跨域资源共享 (CORS (en-US)) 是一种机制,它使用额外的 HTTP 标头告诉浏览器让在一个源(域)上运行的 Web 应用程序有权访问来自服务器的选定资源不同的起源。

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 2022-01-21
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 2012-07-18
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      相关资源
      最近更新 更多