2017-10-06 33 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,因为从站点请求数据,即使它从本地服务器的,是一个异步任务,您的代码将继续运行,而无需等待请求完成。