-1

I am trying to download a PDF from my backend. and i am getting this error.

Blockquote Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.115:5000/journal/download/HP-protein-prediction.pdf-1641052987115.pdf. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 204 Blockquote

I have enabled cors and tried a million things but it's not working. Here's my code Enabling Cors Code

Browser response

and finally my server side and frontend code Server Side

Frontend request using Axios

My Logged Error :

Logging error Error: Network Error

createError createError.js:16

handleError xhr.js:117

dispatchXhrRequest xhr.js:114
xhrAdapter xhr.js:15
dispatchRequest dispatchRequest.js:58
request Axios.js:108
method Axios.js:129
wrap bind.js:9
downloadJournal apiCalls.js:64
onClick ViewArticle.js:23
React 14
unstable_runWithPriority scheduler.development.js:468
React 15
js index.js:9
js main.chunk.js:14047
Webpack 7
Faheem Ahmad
  • 1
  • 1
  • 5
  • try using proxy in your package.json file. – Umair Riaz Jan 04 '22 at 16:53
  • Added this line in the pacakge.json file of server side. Still not working.... "proxy": "http://localhost:5000", – Faheem Ahmad Jan 04 '22 at 16:57
  • No, add in frontend. – Umair Riaz Jan 04 '22 at 16:57
  • add this snippet in package.json ```"proxy": { "/api/*": { "target": "http://localhost:5000", "changeOrigin": true } },``` and use it like `/api/todo` – Umair Riaz Jan 04 '22 at 16:59
  • I copied this snippet to package,json of frontend. and call the api as /api/journal/download/HP-protein-prediction.pdf-1641052987115.pdf 200, but still doesnt work. – Faheem Ahmad Jan 04 '22 at 17:07
  • @UmairRiaz i added the logged error if that helps in identifying the issue. – Faheem Ahmad Jan 04 '22 at 17:13
  • Does this answer your question? [Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i) – LMulvey Jan 04 '22 at 17:16
  • @LMulvey No, i m looking for a solution. – Faheem Ahmad Jan 04 '22 at 17:28

2 Answers2

-1

So as far as I can understand you are trying to download a pdf file in the frontend whenever you hit some API in the backend that sends the pdf to the frontend. I haven't tried the same with the Axios library but you can try using a normal fetch command For Frontend

await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(body)
        })

            .then((response) =>
                response.blob()
            )
            .then((blob) => {
                console.log(blob)
                // Create blob link to download
                const url = window.URL.createObjectURL(
                    new Blob([blob]),
                );
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute(
                    'download',
                    `${e.target.value}.pdf`,
                );

                // Append to html link element page
                document.body.appendChild(link);

                // Start download
                link.click();

                // Clean up and remove the link
                link.parentNode.removeChild(link);
            });

For Backend, I was using Nodejs which has a library file-system or fs

var file = await fs.readFileSync(`location-to-pdf/${req.body.fileId}.pdf`)
   res.contentType("application/pdf");
   res.send(file)

As of my experience if we use app.use(cors()) without specifying any configuration it works without any problem The only doubt I had was about the URL of the API why is that not localhost whereas it's 192.168... if your app is running on localhost maybe you can send it directly to it without the rerouting

  • its not local host because i m specifying the ip in the app.listen function – Faheem Ahmad Jan 04 '22 at 18:29
  • Let me try your solution and see if it works. – Faheem Ahmad Jan 04 '22 at 18:30
  • Maybe you can try to change it to localhost to check if it works because this can create a CORS error. or Can you just show the app.listen because as I remember don't we specify the port to listen on than the IP would like to know how you are doing it – Guneet singh Jan 04 '22 at 18:46
-1

Major browsers its CORS policies prohibit this action, You CANNOT download any data from another domain/ip not the same of your frontend script domain/ip address. Backend & Frontend must be exist in the same domain. For development purpose, you can overcome this limitation by creating new shortcut with this target:

"[Path to Your Chrome]\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
Hamied
  • 27
  • 5