Nicks
Nicks

Reputation: 774

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')
    })
}

Upvotes: 1

Views: 17013

Answers (1)

Vinay Chaudhary
Vinay Chaudhary

Reputation: 318

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.

Upvotes: 1

Related Questions