How to handle redirect request in react to download file on browser.

吃可爱长大的小学妹 提交于 2019-12-23 06:23:30

问题


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

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

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.

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.


回答1:


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



来源:https://stackoverflow.com/questions/48793613/how-to-handle-redirect-request-in-react-to-download-file-on-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!