【问题标题】:Download pdf file from API从 API 下载 pdf 文件
【发布时间】:2017-11-29 04:27:41
【问题描述】:

我正在创建一个在单击按钮后创建和下载 pdf 的函数。我使用 express 作为后端,使用 react/readux/axios 作为前端。

我的后端运行在与前端不同的端口上。

所以我用 axios 调用 API,然后快速创建 pdf 并用 sendFile 响应。

当使用邮递员测试我的发帖请求时,一切正常。

当我从我的 react 应用程序中使用它时,不会下载文件

表达

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 调用

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

【问题讨论】:

    标签: reactjs express redux axios


    【解决方案1】:

    文件下载仅适用于'GET' request。 您可以简单地创建一个接受'GET' request 的 API。 从客户端,在某些操作上您可以致电window.open('server full url with api path')

    通过上面的操作,它开始下载你的文件。

    【讨论】:

      猜你喜欢
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多