问题
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