javascript - 使用 Angular 2 下载 Node 流

标签 javascript node.js angular pdf

我正在尝试使用 Node js 在服务器端生成 PDF,并在 Angular 4 上将其下载到客户端(就像当您按“下载为 PDF”时 Google Drive 所做的那样)。

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

        });
    });
});

在 Angular 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");

        });
}

我收到此错误:无法在“URL”上执行“createObjectURL”,如果我将此行更改为此

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

然后我收到此错误:错误:请求正文不是 blob 或数组缓冲区

我不知道我做错了什么,顺便说一句,有没有一种方法可以轻松下载这个流,而不需要任何像文件保护程序这样的插件?因为如果我只是在浏览器上输入 api 链接,它会自动下载该 pdf 文件。

提前谢谢你,丹尼尔。

最佳答案

我假设 Angular 部分正在客户端浏览器上运行。 为什么不使用 fetch API 向 Node 请求文件?

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

要使用此功能,您需要使用async wait syntax ,因为从站点请求数据,即使是从本地服务器请求数据,也是一个异步任务,并且您的代码将继续运行,而无需等待请求完成。

关于javascript - 使用 Angular 2 下载 Node 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46603039/

相关文章:

css - 从 Typescript Angular 获取 CSS 参数

angular - 在 ngx-bootstrap Datepicker 中动态设置最大日期

javascript - `setInterval` 中的时间问题

Javascript 计时器只是分钟和秒

javascript - 在 javascript 中使用堆栈跟踪记录错误

node.js - 如何通过Elastic API使用自定义模式ID创建新的索引模式?

javascript - 如何在 Ionic 中对图像和其他静态 Assets 进行指纹识别以清除缓存?

javascript - 使用支持 i.e 9 的 XMLHttpRequest 进行 AJAX 文件上传

node.js - npm start 给出错误:server.js 不是有效的 win32 应用程序

node.js - node.js 中的 setTimeout 是如何实现的