2017-06-20 98 views
1

我有一个API,可为我在我网站上的每笔付款生成发票。另一方面,我有一台管理客户端的服务器。客户要求时我需要取pdf。节点(快递) - 通过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。此外,如果我打印的数据,我得到了一个缓冲区,看起来像这样:<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 ... >

在我的客户,我爱可信获取数据:

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和我的客户端中,我就得到了完全相同的缓冲区和二进制文件。由于我将它们发送给客户的方式完全相同,我无法理解哪里可能是我的错误。

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

谢谢你的帮助。

回答

1

你试过吗?

你爱可信要求:

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

You can find documentation on this here.

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

+1

非常感谢你,我早些时候尝试过'data.pipe(res)',但是我没有看到响应类型thingy。 –