javascript - 为什么有时 XMLHttpRequest 会被 CORS 阻止,而我的本地 IP 地址位于 access-control-allow-origin 中?
问题描述
几天以来,我有时在浏览器中遇到错误
Access to XMLHttpRequest at 'https://websiteB.com/file.zlip' from origin 'https://websiteA.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://192.168.0.200' that is not equal to the supplied origin.
据我了解,SOP(同源策略)通常是有效的,并且可以通过 CORS 以通知所有参与者的方式绕过。这仅涉及像 XHR 这样的动态服务器请求。
我的目标是在 websiteA 中使用来自 websiteB 的数据。因此,我在 websiteB 的根目录中保存了一个 .htacces。
RewriteEngine on
RewriteBase /
# allow request from multiple domains (domain1.com|domain2.com|...)
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(websiteA.com)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
</IfModule>
关键是这个错误只是偶尔发生。在测试之前,我总是从浏览器中完全清除缓存。
Mozilla Firefox 的结果:
响应头
HTTP/2 200 OK
date: Mon, 31 Aug 2020 12:31:55 GMT
server: Apache
etag: "1d1cf8-58ffd72bc6380"
last-modified: Tue, 13 Aug 2019 10:53:18 GMT
content-length: 1907960
access-control-allow-origin: http://192.168.0.200
age: 698
accept-ranges: bytes
strict-transport-security: max-age=15768000
X-Firefox-Spdy: h2
请求头
GET /file.zlip HTTP/2
Host: websiteB.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0
Accept: */*
Accept-Language: de,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate, br
Origin: https://websiteA.com
Connection: keep-alive
Referer: https://websiteA.com/
TE: Trailers
据我了解,access-control-allow-origin 应该是 websiteA.com,我的本地网络怎么可能有我的 IP 地址?有没有办法在发送之前清除标题?
更新:我刚刚发现,如果我在浏览调试模式中取消选择启用“http 缓存”它可以正常工作。所以我插入了我的网站
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
在我的 .htaccess
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
但没有任何帮助。有谁知道这里出了什么问题?
解决方案
这是因为您的 CORS 标头与来源不匹配。
从您的响应标题中:
access-control-allow-origin: http://192.168.0.200
从您的请求标头:
Origin: https://websiteA.com
因为http://192.168.0.200
不是https://websiteA.com
,它是违反 CORS 的,浏览器正确地阻止了请求。响应的正确 CORS 标头应该是:
access-control-allow-origin: https://websiteA.com
推荐阅读
- python - 使用 agg 将 max 传递给 pandas df 会产生任意结果
- java - 复制 Jar 文件而不损坏
- python - 如何更改seaborn violinplot中内盒的颜色?
- caching - ubuntu - 无法运行 qtcreator 或其他程序
- php - 将程序代码转换为 Blob 的类
- google-tag-manager - Google Tag Manager - 帮助设置标签以跟踪播放按钮的点击次数和时间戳
- postgresql - 尝试安装 pglogical 时无法访问文件“pglogical”
- chisel - 如何在生成的 Verilog 中使用凿子向量中选定元素的 val 名称
- javascript - 将 Value Json Data 获取到系列名称 Highchart
- c - 如何从特定索引开始获取 argv