我的React应用如何一次下载多个PDF文件?

huangapple go评论77阅读模式
英文:

How can my React App download multiple pdf files at once?

问题

我的应用程序正在接收多个URL,当在浏览器中粘贴时,会自动下载一个PDF文件。我现在执行单个文件下载的方式是使用 window.open(url, "_blank") 和我选择的URL。

我的问题是,当我在forof循环中执行这个操作以打开多个URL时,浏览器会阻止除一个标签之外的所有标签。

我尝试使用Axios和fetch来获取一个Blob,但浏览器的网络选项卡显示GET请求由CORS阻止。如果我可以在浏览器中粘贴URL来执行GET请求,为什么会被阻止?如何才能下载多个文件?

英文:

My app is receiving several urls that, pasted in the browser, automatically downloads a pdf file. The way I do a single file download now is using window.open(url, "_blank") with the url I choose.

My problem is when I do that in a forof loop to open more than one url, the browser blocks all but one tab.

I tried using Axios and fetch to get a blob but the network tab of the browser says the GET is blocked by CORS. How can this be blocked if I can make the GET pasting in the browser? How can I download multiple files?

答案1

得分: 1

CORS是一项基本的安全措施,主要是为了确保您不会滥用用户的权限,从另一个站点访问资源(从用户的计算机上)以确保您的网站不应具有访问权限。它是在浏览器级别强制执行的,更多信息请参见跨源资源共享

您可以通过使用镜像站点/服务来绕过CORS,比如CORS Anywhere;这些服务会代表您在远程计算机上发出请求(意味着您无法访问资源),然后将其带回到您,并附上正确的CORS标头。但是,无法绕过浏览器内部的CORS,因为这将对浏览器构成重大安全漏洞,允许任何站点访问任何资源。

另外,从服务器端发出GET请求然后将资源发送回客户端非常简单。无论如何,没有办法从其他域获取资源,除非有一个单独的(即不是客户端)计算机发出请求。

至于为什么window.open(url, "_blank")有效,您网站中的代码在新窗口中与原始标签页中的代码是隔离的;您无法访问该标签页中的数据,因此浏览器可以无问题地下载文件、打开页面,或者进行其他操作(即没有跨源资源共享的问题发生)。

英文:

CORS is a safety measure in place basically to ensure that you aren't abusing the user by accessing resources from another site as that user (from their machine) that your website should not have access to. It's enforced at the browser level, see Cross-Origin Resource Sharing for more info.

You can get around CORS through a mirroring site/service such as CORS Anywhere; these services make the request for you on the remote machine (meaning you do not have access to the resources as the user) and then send it back to you with proper CORS headers. However, you cannot get around CORS inside the browser itself, as this would be a major security vulnerability for the browser to let any site access any resource.

Alternatively, it is pretty simple to make the GET request on the server side and then send the resource back to the client. Either way, there is no way to get resources from other domains without a separate (i.e. not the client) machine doing the requests.

As for why window.open(url, "_blank") works, your code from your website in your tab is quarantined from the code in the new window; you cannot access the data in that tab, so the browser has no issue downloading the file, opening the page, or whatever it happens to be (i.e. there is no cross-origin resource sharing occuring).

huangapple
  • 本文由 发表于 2023年3月15日 21:24:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75745328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定