【问题标题】:Unable to read octet stream response in node js?无法在节点 js 中读取八位字节流响应?
【发布时间】: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


【解决方案1】:

我已经找到了解决这个问题的方法。我尝试使用buffer 作为true 的superagent 访问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)
}
}

【讨论】:

  • 谢谢,这救了我,但请告诉我如何在 (node-fetch) 库中定义 buffer:true,因为我正在尝试使用 (node-fetch) 实现相同但没有获取无关数据.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 2011-10-14
相关资源
最近更新 更多