node.js Express - 从远程网络服务返回二进制数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30212813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:45:44  来源:igfitidea点击:

Express - Return binary data from distant webservice

node.jspdfexpressbinary

提问by Varkal

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.

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

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

但暂时专注于pdf。我写了这段代码:

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

Based on what I saw here : https://github.com/strongloop/express/issues/1555

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

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

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

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.

我肯定关心 getBinaryData() 的返回,因为这个函数询问了一个外部 Web 服务,当我直接询问这个服务时,我得到了正确的文档。

Thank you in advance for your answers

预先感谢您的回答

回答by Michael Shopsin

Here is my slightly cleaned up version of how to return binary files with Express. I assume that the data is in an object that can be declared as binary and has a length:

这是我稍微清理过的关于如何使用 Express 返回二进制文件的版本。我假设数据位于一个可以声明为二进制并具有长度的对象中:

exports.download = function (data, filename, mimetype, res) {
    res.writeHead(200, {
        'Content-Type': mimetype,
        'Content-disposition': 'attachment;filename=' + filename,
        'Content-Length': data.length
    });
    res.end(Buffer.from(data, 'binary'));
};

回答by Varkal

I found a more simple solution :

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

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

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

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