如何处理重定向请求以响应浏览器上的下载文件。 [英] How to handle redirect request in react to download file on browser.

查看:214
本文介绍了如何处理重定向请求以响应浏览器上的下载文件。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的& JS。请帮助我解决以下问题。

I am new to react & JS. Please help me out in solving below problem.

场景:我从包含以下内容的后端收到 SEE_OTHER 类型的响应文件的URL,我需要在浏览器上下载该文件。

Scenario: I am getting a SEE_OTHER type of response from the backend which contains a URL of the file, I need to download that file on browser.

来自后端的响应类似于:

Response from the backend is something like :

 { status:"SEE_OTHER" 
        context: {
          ...
          ...
          headers: 
               Access-Control-Allow-Methods: ["GET, POST, DELETE, PUT"]
               Access-Control-Allow-Origin: ["*"]
               Location:[url from where file is to be downloaded]
         .....
        }   
 }

I正在尝试从响应中提取URL之后尝试下载文件并执行以下功能:

I'm trying to download the file after extracting URL from the response and execute below function below:

 async download(url) {
    let res = await fetch(URL.format(url));

    if(res.status >= 400) {
      throw Error(`HTTP error: ${res.status}`);
    }
    if(res.status === 200) {
     setTimeout(() => {
       window.location.href = res.url;
     }, 100);
    }
  }  

但是我在浏览器控制台上遇到了错误。

But I'm getting below error on browser console.


无法加载
'www.xyz.com/abc.json'
否'Access-Control- Allow-Origin'标头出现在所请求的
资源上。因此,不允许
访问源‘ http:// localhost:2000 。如果不透明的响应满足您的需求,请将请求的
模式设置为 no-cors,以在禁用CORS的情况下获取资源。

Failed to load 'www.xyz.com/abc.json' No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:2000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

如果我使用此扩展名在chrome上。但是什么是永久解决此问题的方法。

Above code works if I use this extension on chrome. But what is a permanent solution for this problem.

此外,有什么方法可以直接从响应中下载文件。

Also, is there any way I could download file directly from the response.

推荐答案

如果您使用Express,请在后端服务中使用以下程序包解决问题。

If you are using express use the following package in your backend service to solve the issue.

https://github.com/expressjs/cors

问题是由于默认情况下浏览器出于安全原因阻止跨源/跨域访问。请参考以下链接,

The issue is because browsers by default prevent cross origin/domain access for few security reasons. Please refer the following link,

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

这篇关于如何处理重定向请求以响应浏览器上的下载文件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆