Search code examples
javascriptjqueryhtmlxmlhttprequestcross-domain

Why do I need CORS header to request a downloadable link?


I have a link that allows me to download a file when I click on it. Instead of downloading, I am trying to access it with a simple request however I am having CORS problems. I do not have any access to the server side, and therefore everything I have tried so far have failed. If I understand correctly, all suggestions I have found so far needs me to have control over the server (I might be mistaken, but as far as I see server side needs to have a CORS header including my domain or have a jsonp function to be envoked).

Does that mean I am unable to read and parse a file that is already downloadable? If yes, how does it make sense since the file is public and already downloadable when I click the link. Since I am manually able to get the file, shouldn't it be possible to access it with code? Could you suggest me any solution or give something that I can work on? Why the code below do not work as a manual click on the browser would?

var urlString = "http://abc.def.com/download?fileid=123&entity_id=123&sid=123";
$.get(urlString, function(data, status){
alert("Data: " + data + "\nStatus: " + status);});

Solution

  • You are able to download the external script by manually clicking on a link to it because, well, you manually clicked it on it! The browser knows that you authorized access to that URL because you clicked a link that pointed to it. But if a bit of JavaScript accesses that URL in the background, the browser can't be so sure the user is okay with that.

    You're thinking "I'm just trying to download an innocent file, why does the browser not trust me??" But let's consider a scarier scenario. Let's say, instead of trying to access http://innocentsite.com/download, your JavaScript was trying to access https://bankofamerica.com/initiateMoneyTransfer?recipient=OE1&amount=10000. Without even knowing it, the user has just let you send $10,000 to yourself since they were logged in on bankofamerica.com.

    Now, obviously Bank of America (or any other respectable bank) doesn't allow $10,000 transfers to be initiated like that. But hopefully the example gets the idea across -- it would be very dangerous for webpages to be able to make HTTP requests to other domains. That's why CORS headers are required.


    Footnote: If you are hosting your own web server, you might look into setting up a proxy. You could have a URL on your website that automatically retrieves the file from the other website, and serves it on your domain. That way, you can retrieve the file without needing the other website to set CORS headers.