Nicks Nicks - 8 months ago 118
React JSX Question

Download pdf file from API

I am creating a function that creates and download a pdf after button click. I am using express as backend and react/readux/axios as front.

My backend runs on a different port than my front.

So I am calling the API with axios, then express create the pdf and respond with sendFile.

When testing my post request with postman everything works great.

When i using it from my react app does not download the file

express

router.post('/', function( req, res, next){

var data = req.body.data

options = {};
// init html string
var html = ejs.renderFile(__dirname + '/template/facture.ejs', {data: data}, options, function(err, str){
if(err){
return err;
}
return str;
});
// create pdf
conversion({ html: html}, (err, pdf) => {
var output = fs.createWriteStream(`documents/factures/${data.Référence}.pdf`);
pdf.stream.pipe(output);

});

var filepath = path.join(pathToDocument, '/factures/',`${data.Référence}.pdf`);

res.download(filepath);

});


Axios call

export function generatePdf(data){
return dispatch => {

axios.post(`${API_ENDPOINT}api/facture-pdf`,
{ data: data },
{ headers: {
'Content-Type': 'application/json',
'x-access-token': localStorage.getItem('token')
}
})
.then(function (response) {
return response.data;
})
.then( pdf => {
window.open(`${API_ENDPOINT}api/${type}-pdf/${data.Référence}`, '_blank')
})
}

Answer Source

The download for a file works only in case of 'GET' request. You can simply simply make a API that accepts a 'GET' request. And from client side, on some action You can call window.open('server full url with api path').

By doing above the it start downloading your file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download