Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 节点(Express)-通过api使用Express发送pdf_Node.js_Api_Express_Pdf_Axios - Fatal编程技术网

Node.js 节点(Express)-通过api使用Express发送pdf

Node.js 节点(Express)-通过api使用Express发送pdf,node.js,api,express,pdf,axios,Node.js,Api,Express,Pdf,Axios,我有一个api,可以为我网站上的每笔付款生成发票。另一方面,我有一个服务器来管理客户机。当客户要求时,我需要取pdf 我正在使用node/express和axios管理http调用 我成功地从api发送了带有以下代码的pdf: function retrieveOneInvoice(req, res, next) { Order .findOne({_id: req.params.id, user: req.user.id}) .exec((err, or

我有一个api,可以为我网站上的每笔付款生成发票。另一方面,我有一个服务器来管理客户机。当客户要求时,我需要取pdf

我正在使用node/express和axios管理http调用

我成功地从api发送了带有以下代码的pdf:

function retrieveOneInvoice(req, res, next) {
    Order
        .findOne({_id: req.params.id, user: req.user.id})
        .exec((err, order) => {
            if(err) {

            } else if (!order) {
                res.status(404).json({success: false, message: 'Order not found!'});
            } else {
                const filename = order.invoice.path;
                let filepath = path.join(__dirname, '../../../invoices' ,filename);

                fs.readFile(filepath, function (err, data){
                    res.contentType("application/pdf");
                    res.end(data, 'binary');
                });
            }
        });
}
这部分工作很好,我可以获取并保存pdf。此外,如果我打印数据,我会得到一个如下所示的缓冲区:

在我的客户端上,我使用axios获取数据:

function retrieveInvoice(Config) {
    return function(orderId, done) {
        axios({
            url: `${Config.apiUrl}/invoices/${orderId}`,
            method: 'get'
        }).then(
            (res) => { return done(null, res.data) },
            (err) => { return done(err) }
        )
    }
}
最后,我尝试通过调用前一个函数将其发送到客户端:

Api.retrieveInvoice(orderId, (err, data) => {
        if(err) {

        } else {
            res.contentType("application/pdf");
            res.end(new Buffer(data, 'binary'), 'binary');
        }
    });
这就是我的问题所在。我总是收到空白页。我尝试过使用和不使用缓冲区,如下所示:

res.contentType("application/pdf");
res.end(data, 'binary');
并且没有“binary”参数。如果我将数据同时记录在api和客户机中,则得到完全相同的缓冲区和二进制文件。由于我将它们以完全相同的方式发送给客户,我只是不明白哪里可能是我的错误

我希望我能给你足够的信息来帮助我,如果我缺少任何东西,我会添加所有可以帮助潜在助手的东西

谢谢你的帮助。

你试过这个吗

您的axios请求:

axios({
    url: `${Config.apiUrl}/invoices/${orderId}`,
    method: 'get',
    responseType: 'stream'
}).then(
    ...
)
以及您的回拨:

Api.retrieveInvoice(orderId, (err, data) => {
    if (err) {
        // handle error
    } else {
        res.contentType("application/pdf");
        data.pipe(res);
    }
});


默认的
responseType
'json'
,因此更改它应该可以解决问题。

非常感谢,我之前尝试过
data.pipe(res)
,但没有看到响应类型。