node.js - 节点: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);
});
现在我正在尝试用这些数据做两件事。
- 将其写入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();
- 尝试将其发送到将创建 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 文件正在正确生成。
解决方案
处理二进制数据时,必须将编码设置为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
,我推荐使用request
or got
,所以你可以.pipe
直接到文件或表达res
推荐阅读
- angular - (SystemJS) 导出未定义
- javascript - 获取所选类 vuejs 的值
- python-3.x - 无法在 Windows 10 服务器上安装 python 库
- wpf - 添加时导致新的 ListView 项目背景闪烁
- vba - VBA:根据数据中的类别拆分excel文件
- sql - 检查每个用户的每个值之间的 datediff 标准
- angular - 未找到模块:错误:无法解析 '@angular/cdk/tree' '@angular/material/tree'
- oracle - 一般数据库问题 - 索引 ID 字段性能与限制(顶部)性能(Salesforce)
- c# - Why IIS CredentialManagement don't wor perfect with IIS
- r - 突出显示由选择项指向的 R 传单多边形(不单击它)