![](/img/trans.png)
[英]Unable to convert response data of octet-stream to Zip file and download it
[英]Unable to read octet stream response in node js?
我有一个 API 将响应作为“八位字节流”返回。 这是同样的 swagger 定义。
responses: {
'200': {
description: 'Will return the pdf for an invoice',
content: {
'application/octet-stream': {
schema: '',
},
},
},
}
通过邮递员和 swagger ui,我可以将响应保存为 PDF 文件。 但是对于节点,我无法编写 pdf 文件。
下面是节点js调用API的代码。
var fs = require('fs');
var request = require('request');
let headers = {
'Content-Type': 'application/json',
'accept': "application/octet-stream",
}
let body = {
"invoiceId": "343",
"slCompId": 243,
"platfromCompId": "4620816365013235830"
}
request.post({
headers,
url: 'http://localhost:3001/invoice/',
json: body
},
function (error, response, body) {
console.log(response);
console.log("response");
fs.writeFile('a.pdf', response.body, 'binary')
});
编辑:
写入的 PDF 文件已损坏。 文件中没有任何内容,PDF 查看器在打开文件时出现错误。
我找到了解决这个问题的方法。 我尝试使用buffer
为true
超级代理访问 API。
async function getData() {
try {
var fs = require('fs');
let res = await superagent
.get('https://localhost:3000/invoice')
.set("Content-Type", "application/json")
.set("accept", "application/octet-stream")
.buffer(true).disableTLSCerts()
console.log(res)
fs.writeFile('a.pdf',res.body)
}
catch(error) {
console.log("error " + error)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.