Download pdf file from API

℡╲_俬逩灬. 提交于 2019-12-25 14:46:43

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/47545044/download-pdf-file-from-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!