【问题标题】:Node: Express: How to handle application/octet-stream;charset=;UTF-8 response?节点:Express:如何处理 application/octet-stream;charset=;UTF-8 响应?
【发布时间】:2020-03-30 15:47:00
【问题描述】:

我有一个 node-express 应用程序。 在那里,我正在尝试调用一个 API,该 API 将原始 xlsx 对象响应为

'Content-Type' : 'application/octet-stream;charset=;UTF-8'

编写我调用 API 的方式:

var unirest = require("unirest");

var reqClient = unirest("POST", "https://api.application.com/getExcel");
reqClient.headers({ "Authorization": "Bearer " + req.session.passport.user.token, 
"content-type": req.headers['content-type'], "application/json"});
reqClient.type("json");
reqClient.send(JSON.stringify(requestbody));
reqClient.end(function(res) {
if (res.error) throw new Error(res.error);
console.log(res.body);
});

现在我正在尝试用这些数据做两件事。

  1. 将其写入 Excel 文件。 以下是我正在尝试的代码:
    let data = res.body // res is the response coming from the API
    let buf = Buffer.from(data);
    excelfile = fs.createWriteStream("result.xlsx");
    excelfile.write(buf);
    excelfile.end();
  1. 尝试将其发送到 UI 将在其中创建 excel 文件。 下面是我的代码:
    let data = res.body // res is the response coming from the API
    let buf = Buffer.from(data);
    response.write(buf); //response is the response to the request to ui
    response.end();

因此,在这两种情况下,文件都已损坏。

但是 API 响应是完美的,因为当它直接被 UI 使用时,xlsx 文件正在正确生成。

【问题讨论】:

  • 1.试试fs.writeFile("result.xlsx", buf, "binary", (err) =>{});
  • 请说明您是如何调用 API 的。看来您正在使用 axios 或类似名称。
  • @KevinHernandez 在尝试打开文件时仍然出错。 “我们发现 'result.xlsx' 中的某些内容存在问题。您希望我们尽可能多地恢复吗?如果您信任此工作簿的来源,请单击是。”
  • 这很容易解决,使用 API 请求更新代码。
  • @MarcosCasagrande 我已更新 API 调用代码stackoverflow.com/posts/59199767/revisions

标签: node.js express utf-8 content-type unirest


【解决方案1】:

处理二进制数据时,必须将编码设置为null

reqClient.encoding(null)
reqClient.encoding(null)
reqClient.end(function(res) {
    if (res.error) {
       return response.status(500).send('error');
    }

    // res.body is now a buffer
    response.write(res.body);
    response.end();
});

否则,数据将转换为UTF-8,您无法将UTF-8转换回二进制并获得相同的数据,这就是您所做的:

Buffer.from(res.body)

推荐的做法是直接使用streams,我在unirest没有看到简单的方法,我推荐使用request或者got,所以可以直接.pipe文件或快递res

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2017-11-03
    • 2012-03-31
    • 2021-07-09
    • 2014-06-08
    • 2021-08-31
    • 1970-01-01
    相关资源
    最近更新 更多