2017-06-20 106 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。 –