跨域请求的一个问题

2019-12-22 14:28:40 +08:00
 leosirius666a

自己用 XHR 对象向 google.com 发起 get 请求,浏览器会报

Access to XMLHttpRequest at 'https://www.google.com/' from origin 'http://localhost:52331' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我用浏览器直接访问 google.com ,不也是在不同的域吗,为什么没有跨域问题。

2718 次点击
所在节点    程序员
16 条回复
lhx2008
2019-12-22 14:30:35 +08:00
不要带自定义头
lhx2008
2019-12-22 14:31:27 +08:00
说错了,这种 Google 回的时候要有一个额外的头
leosirius666a
2019-12-22 14:31:56 +08:00
我什么都没做,代码这样的
```js
let xhr = new XMLHttpRequest();
xhr.open("get", "https://www.google.com", true);
xhr.send(null);

xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
alert(xhr.responseText);
} else {
alert("Request was unsuccessful: " + xhr.status);
}
}
}
```
1OF7G
2019-12-22 14:32:27 +08:00
这是浏览器对网页施加的限制,而不是 系统或网络协议或某种魔法 对浏览器的限制。
leosirius666a
2019-12-22 14:34:24 +08:00
@1OF7G 我知道是浏览器在 response 成功返回后浏览器自己把返回 block 了,但是为什么直接访问它就没有 block
1OF7G
2019-12-22 14:42:01 +08:00
@leosirius666a 浏览器只是阻止把 google.com 的内容给到其它第三方网站的 JS,如你的 localhost。如果你直接访问,根本没有第三者参与进来,还防范谁呢?
beastk
2019-12-22 14:48:41 +08:00
js 限制
VDimos
2019-12-22 14:53:34 +08:00
。。。跨域不是这个意思,跨域是指你的域名的脚本加载了不是你域名的内容。。。
leosirius666a
2019-12-22 15:03:08 +08:00
@VDimos 原来是这样。。
zsdroid
2019-12-22 15:04:07 +08:00
cst4you
2019-12-22 16:18:45 +08:00
leosirius666a
2019-12-22 16:32:21 +08:00
ssshooter
2019-12-22 16:50:44 +08:00
x66
2019-12-22 20:37:01 +08:00
“chrome.exe” –disable-web-security –user-data-dir=xxx
beastk
2019-12-22 21:43:34 +08:00
其实你还没搞懂。localhost 是本地域,有特权,不信你用 ie 使用 ajax,http https 是网络域,脚本资源遵循同源策略。
beastk
2019-12-22 21:49:21 +08:00
@beastk #15 勘误,在 ie 下,file 协议有特权

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/631221

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX