[英]Why the same GET request gets blocked by CORS when called within javascript but allowed from HTML src?
I was embedding some large images with react query to provide a loading effect on slow connections when I encountered this CORS issue I did not understand.当我遇到这个我不明白的 CORS 问题时,我正在嵌入一些带有反应查询的大图像以提供对慢速连接的加载效果。
I'm not getting why it's no problem for the browser to import resources from external servers when the request is performed in the HTML.我不明白为什么在 HTML 中执行请求时,浏览器从外部服务器导入资源没有问题。
For example, this is a valid image fetch:例如,这是一个有效的图像获取:
<img src={"https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg"}/>
it gets rendered with no problem.它可以毫无问题地渲染。
When performing the same fetch from javascript, you get CORS to block your response.当从 javascript 执行相同的提取时,您会得到 CORS 来阻止您的响应。
For example:例如:
fetch("https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg");
will be blocked.将被阻止。
They are both GET requests, and inspecting the response headers on the network tab they look the exact same.它们都是 GET 请求,并且检查网络选项卡上的响应标头,它们看起来完全相同。
Is it a desired browser behavior?这是理想的浏览器行为吗? If so, how is it a safety feature?如果是这样,它如何成为安全功能?
If not, how to get around this, in order to fetch simple requests ?如果没有,如何解决这个问题,以获取简单的请求?
Is it a desired browser behavior?这是理想的浏览器行为吗? If so, how is it a safety feature?如果是这样,它如何成为安全功能?
Keep in mind that the image might not be generally available.请记住,该图像可能无法普遍使用。 It could be password protected, or on a company intranet.它可以受密码保护,也可以在公司内部网上。 Consider a hypothetical popular Intranet application that has a common URL that displays internal company financial data on a graph.考虑一个假设的流行 Intranet 应用程序,它有一个常见的 URL,它在图表上显示公司内部财务数据。
When you use fetch
the image data is made available to JavaScript.当您使用fetch
时,图像数据对 JavaScript 可用。 The JavaScript can then do whatever it likes with the image, including sending it to the person who wrote the JavaScript.然后 JavaScript 可以对图像做任何喜欢的事情,包括将其发送给编写 JavaScript 的人。 That hypothetical financial data would be leaked.假设的财务数据将被泄露。
When you use an <img>
element, the image is just displayed in the page and the user can see it.当您使用<img>
元素时,图像只是显示在页面中并且用户可以看到它。 The security problems are low and JavaScript can't access the data in the image.安全问题低,JavaScript 无法访问图像中的数据。
Adding a crossorigin
attribute to the <img>
would let JavaScript access the data in it … and would also require permission from CORS before the image could be displayed.向<img>
添加crossorigin
属性将使 JavaScript 访问其中的数据……并且还需要 CORS 的许可才能显示图像。
If not, how to get around this, in order to fetch simple requests?如果没有,如何解决这个问题,以获取简单的请求?
Grant permission with CORS or fetch the image with code that isn't running client-side in a browser.使用 CORS 授予权限,或者使用不在浏览器客户端运行的代码获取图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.