i am using window.fetch for downloading file , but is generating error file on server not on local

Viewed 401
function download(id) {
    $.get(base_url + "account/download/" + id, function (data) {
        var data = JSON.parse(data);
        if (data.code == 1) {
            console.log(data)
//data.filePath = "https://s3.amazonaws.com/stores-products/8c0123ef4a1d685bbf50582ffb461573.jpg"
            fetch(data.filePath, { mode: 'no-cors', method: 'GET' })
                .then(resp => resp.blob())
                .then(blob => {
                    console.log(blob)
                    const url = window.URL.createObjectURL(blob);
                    console.log(url)
                    const a = document.createElement('a');
                    //a.style.display = 'none';
                    a.href = url;
                    a.download = data.fileName;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                })
                .catch(() => bootbox.alert("Unable to Download File"));
        }
        else if (data.code == 0) {
            bootbox.alert(data.msg);
        }
    });
}

under get api call I am using fetch with url of amazon s3 , its working fine on local but it generating error file on server , please review my code and let me know the issue in this code. I did not getting any error message , but downloaded file , when I am opening it show error to load file.

1 Answers

In order to be able to fetch resources cross-origin you need to understand and properly configure CORS headers, i.e. the server needs to send the right Access-Control-Allow-Origin and Access-Control-Allow-Methods. Otherwise browser security will prohibit the request.

Trying to circumvent this with {mode: 'no-cors'} does not work as one might expect: although 'no-cors' will ignore the CORS headers of the server the response content will then be inaccessible to your javascript code, see the documentation for Request.mode:

no-cors — Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers. If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are simple headers. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.

This is due to the resulting Response's type being opaque preventing you from accessing its actual contents.

For further explanation see this excellent answer to a similar question.

So what you need to do is to use {mode: 'cors'} and have the server appropriately configured to allow for cross-origin requests from your frontend domain.

Related