ani*_*nij 5 content-type utf-8 node.js express unirest
我有一个节点表达应用程序。在那里,我尝试调用一个 API,该 API 将原始 xlsx 对象响应为
'内容类型':'应用程序/八位字节流;字符集=;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);
});
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试用这些数据做两件事。
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();
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
因此,在这两种情况下,文件都会损坏。
但 API 响应是完美的,因为当UI直接使用它时,xlsx 文件会正确生成。
处理二进制数据时,必须将编码设置为null
reqClient.encoding(null)
Run Code Online (Sandbox Code Playgroud)
reqClient.encoding(null)
Run Code Online (Sandbox Code Playgroud)
否则,数据将被转换为二进制UTF-8
,并且您无法将其转换UTF-8
回二进制并获得相同的数据,这就是您正在做的事情:
Buffer.from(res.body)
Run Code Online (Sandbox Code Playgroud)
推荐的方法是直接使用流,我在 中没有看到以简单的方式执行此操作的方法 unirest
,我建议使用request
or got
,这样您可以.pipe
直接到文件或表达res