【发布时间】:2020-02-12 12:34:06
【问题描述】:
我有一个以“八位字节流”形式返回响应的 API。这是相同的招摇定义。
responses: {
'200': {
description: 'Will return the pdf for an invoice',
content: {
'application/octet-stream': {
schema: '',
},
},
},
}
通过邮递员和 swagger ui,我可以将响应保存为 PDF 文件。但是使用节点我无法编写 pdf 文件。
下面是nodejs调用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 查看器在打开文件时出现错误。
【问题讨论】:
-
“我无法写入 pdf 文件”是什么意思?
-
我收到了写 PDF 文件的回复。我不会写。
-
“我不会写”是什么意思?你有错误吗?文件是否已创建但为空白?它有助于具体了解 Stackoverflow。此外,您没有将回调传递给 writeFile,因此它可能会出错并且有些东西正在吃错误nodejs.org/api/…
-
写入的文件已损坏。文件内没有任何内容,PDF 查看器在打开文件时出现错误。
-
您是否尝试写
body而不是response.body?此外,您可以使用流而不是先缓冲整个文件:github.com/request/request#streaming。此外,request从今天起已弃用,因此您可能可以使用 superagent,但关于流式传输的观点仍然存在。
标签: javascript node.js rest superagent