首页 > 解决方案 > 节点:Express:如何处理 application/octet-stream;charset=;UTF-8 响应?

问题描述

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

“内容类型”:“应用程序/八位字节流;字符集=;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. 尝试将其发送到将创建 excelfile的UI 。下面是我的代码:
    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 文件正在正确生成。

标签: node.jsexpressutf-8content-typeunirest

解决方案


处理二进制数据时,必须将编码设置为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)

推荐的方法是直接使用流,我在 中没有看到简单的方法 unirest,我推荐使用requestor got,所以你可以.pipe直接到文件或表达res


推荐阅读