【发布时间】: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);
});
现在我正在尝试用这些数据做两件事。
- 将其写入 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();
- 尝试将其发送到 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