doe*_*ute 2 javascript pdf node.js express
我已经尝试了各种方法来让它发挥作用。我正在尝试从节点上的 API 请求 PDF,然后将其发送回最初调用它的客户端。
\n\n目前我只想在节点服务器上成功保存并查看 PDF。
\n\n问题是当我打开 PDF 文件时它总是空的(即使它的大小为 30kb)。
\n\n基本流程是这样的(删除了一些位,但下面的代码可以正常工作并返回 PDF)
\n\n// We pass through session ID\'s, request dates etc through in body\napp.post("/getPayslipURL", function(client_request, res) {\n\n // create request, which will simply pass on the data to the database (In order to get the NI number we need for the pay API)\n const NI_NUMBER_REQUEST = db_api.createRequestTemplate({\n body: JSON.stringify(client_request.body)\n });\n\n // Create a chain of HTTPS Requests, Starting with our call to the DB\n requestPromise(NI_NUMBER_REQUEST)\n .then((db_response) => { \n const PAY_API_OPTIONS = /*Code to generate options based on furhter DB info (Includes dates etc)*/\n return requestPromise(PAY_API_OPTIONS); // Call pay API\n })\n .then((pay_pdf_data) => { \n\n console.log(typeof pay_pdf_data); // It\'s a string\n // At this point I can log pay_pdf_data, But if I try to save it to file it\'s always empty\n // No matter how I encode it etc\n\n fs.writeFile("./test.pdf", pay_pdf_data, \'binary\', function(err) {\n if(err) {\n return console.log(err);\n }\n console.log("The file was saved!");\n }); \n\n })\n .catch(err => `Error caught: ${console.log}`) // Catch any errors on our request chain\n });\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我已经尝试使用/不使用二进制标志进行保存,正如文件保存以及请求本身中其他帖子中所建议的那样。也尝试过各种类型的解码方法,我总是得到一个空的PDF保存。
\n\n我的返回数据看起来像这样(更大,当保存为 test.pdf 时,我得到一个 30kb 文件,如前面提到的)
\n\n%PDF-1.4\n%\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\n1 0 对象\n 0 对象\n<\n\n
我发现一篇文章说关于将数据一直通过管道传输,我感觉我的 pdf_data 在转换为字符串时已损坏
\n\n有什么想法我将如何使用当前的设置来做到这一点?
\n\ne/ RequestPromise 是一个库,如果更容易的话也可以使用标准请求库
\n\nhttps://github.com/request/request-promise - \n https://github.com/request/request
\n\n谢谢!
\n您的代码不起作用,因为底层request库(由request-promise)需要将选项encoding设置null为二进制数据 - 请参阅https://github.com/request/request#requestoptions-callback。
以下是使用该模块下载二进制数据的方法 -
app.post("/getPayslipURL", function(client_request, res) {
const NI_NUMBER_REQUEST = db_api.createRequestTemplate({
body: JSON.stringify(client_request.body),
encoding: null
});
requestPromise(NI_NUMBER_REQUEST)
.then((db_response) => {
const PAY_API_OPTIONS = /*Code to generate options based on furhter DB info (Includes dates etc)*/
return requestPromise(PAY_API_OPTIONS); // Call pay API
})
.then((pay_pdf_data) => {
fs.writeFile("./test.pdf", pay_pdf_data, 'binary', (err) => {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
})
.catch(err => `Error caught: ${console.log}`) // Catch any errors on our request chain
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2849 次 |
| 最近记录: |