PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] Why the same GET request gets blocked by CORS when called within javascript but allowed from HTML src?

 October 13, 2022     axios, cors, fetch, javascript, react-query     No comments   

Issue

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.

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.
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.
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.

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?


Solution

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.

When you use fetch the image data is made available to JavaScript. The JavaScript can then do whatever it likes with the image, including sending it to the person who wrote the 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. The security problems are low and JavaScript can't access the data in the image.

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.

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.



Answered By - Quentin
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing