Node.js:服务dynamicpdf,空着

我有一个节点服务,从API获取pdf并提供该pdf。

当我curl或直接打开API,我看到正确的PDF。

但是,当我从我的节点应用程序服务,我得到一个空的PDF。

这是我的代码的PDF渲染的部分。

} else if (options.type === 'pdf') { res.writeHead(200, {'content-type' : 'application/pdf', 'content-disposition': 'attachment; filename=invoice.pdf'}); res.end(data.invoice); 

我有console.log'ed data.invoice知道这是正确的东西。

typeof(data.invoice)给出string; 但我也试过res.end(new Buffer(data.invoice)); 哪个也没用

这里是我的代码提取数据的部分

 var http_options = { method : options.method , host : Config.API.host , path : options.path , port : Config.API.port , headers : options.headers }; var req = http.request(http_options, function (response) { var raw_response = ""; response.on('data', function (response_data) { raw_response += response_data.toString(); }); response.on('end', function () { if (response.statusCode !== 200) { cb(raw_response); } else { cb(false, raw_response); } }); }); req.setTimeout(timeout, function () { req.abort(); cb("API connection timed out"); }); req.on('error', function (error) { cb("API error while requesting for " + options.path + '\n' + error + '\n' + "http options: " + JSON.stringify(http_options) }); req.end(); 

在接收PDF时, toString()和concatenation很可能会破坏它。 尝试将raw_response写入文件(您可以使用writeFileSync()因为这只是一次性testing),并使用curl检索的同一PDF进行逐字节比较。

请注意,如果string转换的过程损坏了它,在发送之前尝试将其转换回缓冲区将无济于事。 你将不得不把整个事情作为一个缓冲区从头到尾。

由于您不打算在传输中修改或读取此数据,因此我build议您只使用pipe道function来pipe理从responsereq所有数据。 这个问题有一个很好的例子 ,但这里是一个摘录。

 req.on('response', function (proxy_response) { proxy_response.pipe(response); response.writeHead(proxy_response.statusCode, proxy_response.headers); }); 

请注意,没有任何理由将来自缓冲区响应的数据块转换为其他数据,只需将它们作为未修改的缓冲区写入,然后对其进行stream式处理(这是pipe道将为您执行的操作),而不是累积它们以获得最大效率和node.jsstream时髦点)。