为什么从浏览器发送而不是从终端发送时,CORS 会阻止我的 Http 请求

问题描述

我对 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 域的请求。但是,当我从不属于 google 域的终端 curl 时,我收到了 200 条 HTML 响应,等等。

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

谢谢^.^

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)