节点(Express) – 通过api以快递方式发送pdf

我有一个API,为我在网站上的每笔付款生成发票。 另一方面,我有一个服务器来pipe理客户端。 客户要求时我需要取pdf。

我使用node / express和axios来pipe理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。 此外,如果我打印数据,我得到了如下的缓冲区: <Buffer 25 50 44 46 2d 31 2e 34 0a 31 20 30 20 6f 62 6a 0a 3c 3c 0a 2f 54 69 74 6c 65 20 28 fe ff 29 0a 2f 43 72 65 61 74 6f 72 20 28 fe ff 29 0a 2f 50 72 6f ... >

在我的客户端,我用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'); 

没有“二进制”参数。 如果我将数据logging在api和我的客户端,我得到了完全相同的缓冲区和二进制文件。 因为我把它们发给客户的方式完全一样,我不明白哪里可能是我的错误。

我希望我能够向你提供足够的信息来帮助我,我什么都不知道,我会添加一切可以帮助潜在的帮手。

感谢您的帮助。

你尝试过吗?

您的axios请求:

 axios({ url: `${Config.apiUrl}/invoices/${orderId}`, method: 'get', responseType: 'stream' }).then( ... ) 

和你的callback:

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

你可以在这里find关于这个文件。

默认的responseType'json' ,所以改变这个可以解决问题。