Express - 从 Web 服务返回二进制数据 [英] Express - Return binary data from webservice

查看:29
本文介绍了Express - 从 Web 服务返回二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 Express 返回一些二进制数据.在示例中,它是 PDF,但理论上,它可以是任何类型的文件.

I try to return some binary data with Express. In the example, it's a PDF but theorically, this can be any sort of file.

但现在只关注 pdf.我写了这段代码:

But focus on the pdf for the moment. I wrote this code :

app.get('*', function (req, res) {
    getBinaryData(req.url,
        function (answer) {
            res.type('pdf');
            res.end(new Buffer(answer, 'binary'));
        },
        function (error) {
            res.setHeader('Content-Type', 'text/plain');
            return res.end(error);
        }
    );
});

根据我在这里看到的:https://github.com/strongloop/express/issues/1555

但是,我得到了一个页数正确的 pdf 文件,正确的标题....但是所有页面都是空白的

But, i get a pdf file with the right number of pages, right title.... but all the pages are blank

我很担心 getBinaryData() 的返回,因为这个函数请求了一个外部 Web 服务,当我直接请求这个服务时,我得到了正确的文档.

I'm sure concern the return of getBinaryData(), because this function asked an external Web Service and when I asked directly this service, I got the right document.

提前感谢您的回答

推荐答案

我找到了一个更简单的解决方案:

I found a more simple solution :

request(req.url).pipe(res);

这会将来自远程 Web 服务的原始响应直接传递给我的响应!无论文件类型如何,我都得到了正确的文件.

This pipes the original response from distant Web Service directly to my response! I got the correct file regardless of the file type.

这篇关于Express - 从 Web 服务返回二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆