2017-10-06 32 views
0

我想在服務器端使用節點js並在角4上下載它在客戶端上的PDF(類似谷歌驅動器時,你按下載爲PDF)。下載節點流與角2

節點JS代碼看起來是這樣的:

var pdf = require('html-pdf'); 

app.get('/pdf/contacts', function(req, res) { 
    Contact.find(function(error, response) { 
     res.render('pdfs/views/contacts', {name: 'Daniel Pacuraru', contacts: response}, function(error, thtml) { 

      var opts = { 
       "format": "A4", 
       "orientation": "portrait", 
       "border": "0.4in" 
      }; 

      pdf.create(thtml, opts).toStream(function(err, stream){ 
       res.attachment('pdfname.pdf'); 
       stream.pipe(res); 
      }); 

     }); 
    }); 
}); 

在角4身邊,我得到了這樣的事情:

import * as FileSaver from 'file-saver'; 

downloadContacts(): Promise<any> { 
    return this.http 
     .get('http://localhost:3000/pdf/contacts') 
     .toPromise() 
     .then(response => { 

      FileSaver.saveAs(response, "testdata.pdf"); 

     }); 
} 

我得到這個錯誤:Failed to execute 'createObjectURL' on 'URL'如果我改線進入此

FileSaver.saveAs(response.blob(), "testdata.pdf"); 

然後我得到這個錯誤:Error: The request body isn't either a blob or an array buffer

我無法弄清楚我做錯了什麼,btw有沒有一種方法可以輕鬆下載這個流而不需要任何插件如文件保護程序?因爲如果我只是輸入並在瀏覽器上的api鏈接,它會自動下載我的PDF文件。

先謝謝你了,丹尼爾。

回答

0

我假設角部分正在客戶端瀏覽器上運行。 爲什麼不使用fetch API來請求文件到節點?

const response = await fetch("http://localhost:3000/pdf/contacts"); 
const blob = await response.blob(); 

要使用這個,你需要使用async awaitsyntax,因爲從站點請求數據,即使它從本地服務器的,是一個異步任務,您的代碼將繼續運行,而無需等待請求完成。