简体   繁体   English

JS 使用重定向获取 URL

[英]JS Fetch URL with redirection

I have a link A that redirects to a link B which is a PHP endpoint to download a text file.我有一个链接 A 重定向到链接 B,该链接 B 是一个 PHP 端点,用于下载文本文件。 I was running the following code and it was working before:我正在运行以下代码,并且之前可以正常工作:

const file = await fetch(linkA).then(res => res.text())

But lately, the server for link A stopped redirecting me to link B giving CORS error.但最近,链接 A 的服务器停止将我重定向到链接 B,给出 CORS 错误。 but if I copy link A and paste it on the address bar, the browser will be redirected to link B and will start downloading the file immediately.但是如果我复制链接 A 并将其粘贴到地址栏上,浏览器将被重定向到链接 B 并立即开始下载文件。 And if I just change linkA with linkB directly in the code, I can download it without any CORS error, but in the app, I will only have Link A.如果我只是在代码中直接将linkB linkA我可以下载它而不会出现任何CORS错误,但在应用程序中,我将只有Link A。

So my question is : can I get the link B programmatically before fetching it?所以我的问题是:我可以在获取链接 B 之前以编程方式获取它吗?

I wished to share the links but they are private, unfortunately.我想分享这些链接,但不幸的是,它们是私人的。

EDIT编辑

just to give more information.只是为了提供更多信息。 Link A is like an authentication endpoint, I need to pass username and password as query parameters.链接 A 就像一个身份验证端点,我需要将用户名和密码作为查询参数传递。 So the server authenticates it and redirects me to another endpoint (I believe that it's a temporary link) with the file I want to download which I can use in the fetch method without cors error.因此,服务器对其进行身份验证并将我重定向到另一个端点(我相信它是一个临时链接),其中包含我想要下载的文件,我可以在fetch方法中使用它而不会出现 cors 错误。

EDIT 2编辑 2

It seems that the server of link A only redirects me if I am from the same origin, so what I believe to be possible is to create a sort of silent window that navigate to link A window.location.href and after it gets redirected, I would need to block the file to not be downloaded automatically, get the link B and fetch it in the app... but I don't have a clue how to do it.如果我来自同一个来源,链接 A 的服务器似乎只会重定向我,所以我认为可能的是创建一种无声 window 导航到链接 A window.location.href并在它被重定向之后,我需要阻止文件不自动下载,获取链接 B 并在应用程序中获取它......但我不知道该怎么做。

This is due to linkA server may have restricted it's access to same origin only.这是因为 linkA 服务器可能已限制它只能访问同一来源。

And, if you are using using browser, it will work as you are directly hitting the URL which is technically same origin, but when you are using ajax call you are calling it from some different origin.而且,如果您使用的是浏览器,它会起作用,因为您直接点击 URL 这在技术上是相同的来源,但是当您使用 ajax 调用时,您是从一些不同的来源调用它。

If you still want to use it seriously, then you can use cors anywhere.如果您还想认真使用它,那么您可以在任何地方使用cors。 -> https://www.npmjs.com/package/cors-anywhere -> https://www.npmjs.com/package/cors-anywhere

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM