I have an api which provides a json-object with a link to the pdf
{ pdf_link: 'http://localhost:3000/logs.pdf' }
When user clicks on the file name, I want to open this pdf in a separate browser tab.
I tried giving the url as href in an a
tag
<a href={response.pdf_link} target='_blank'>{FileName}</a>
But when I click on the link, pdf is getting downloaded, not opening in a browser tab.
I found this blog post and tried the following.
import axios from 'axios';
import React from 'react';
export const PdfLink = ({ apiResponse }: any) => {
const showFile = (blob: Blob, fileName: string) => {
const newBlob = new Blob([blob], {type: 'application/pdf'});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
const data = window.URL.createObjectURL(newBlob);
const link = document.createElement('a');
link.href = data;
link.download = fileName;
link.click();
setTimeout(() => {
window.URL.revokeObjectURL(data);
}, 100);
};
const onClickLink = () => {
axios({
method: 'GET',
responseType: 'blob',
url: apiResponse.pdf_link,
})
.then(r => showFile(r.data, apiResponse.fileName));
};
return (
<span className='link' onClick={onClickLink}>
file.pdf
</span>
);
};
But this is failing at the api call to get the file blob.
axios({
method: 'GET',
responseType: 'blob',
url: apiResponse.pdf_link,
})
Error: Access to XMLHttpRequest at 'http://localhost:3005/file.pdf' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The below image shows the request and response headers of the api call
I know that the above error is due to cors but in the server, I am allowing requests from other origins as well
app.use(KoaCors({ origin: '*', credentials: true }));
What am I doing wrong?