Node.js中Axios获取的octet-stream结构解析及转JSON方法求助
Axios调用API返回乱码的解决方法
1. 先排查响应头关键信息
首先打印响应头,确认数据是否被压缩、以及正确的字符编码:
axios.get('http://api.com/filesList', { responseType: 'arraybuffer' }) .then(response => { console.log('响应头:', response.headers); // 后续处理逻辑 });
重点看两个字段:
content-encoding:如果是gzip/deflate,说明数据是压缩过的,需要先解压content-type:从中提取charset参数,确定文本的编码格式(比如gbk、utf-8)
2. 处理压缩数据
如果响应头显示数据被压缩,用Node.js内置的zlib模块解压:
const zlib = require('zlib'); axios.get('http://api.com/filesList', { responseType: 'arraybuffer' }) .then(response => { const buffer = Buffer.from(response.data); const encoding = response.headers['content-encoding']; if (encoding === 'gzip') { zlib.gunzip(buffer, (err, decodedBuffer) => { if (!err) handleDecodedBuffer(decodedBuffer, response.headers['content-type']); }); } else if (encoding === 'deflate') { zlib.inflate(buffer, (err, decodedBuffer) => { if (!err) handleDecodedBuffer(decodedBuffer, response.headers['content-type']); }); } else { handleDecodedBuffer(buffer, response.headers['content-type']); } });
3. 处理非UTF-8编码的文本
如果响应头指定了非UTF-8编码(比如gbk),用iconv-lite转码:
先安装依赖:
npm install iconv-lite
然后实现转码和解析逻辑:
const iconv = require('iconv-lite'); function handleDecodedBuffer(buffer, contentType) { // 提取字符编码,默认UTF-8 const charsetMatch = contentType?.match(/charset=([^;]+)/); const charset = charsetMatch ? charsetMatch[1].toLowerCase() : 'utf-8'; // 转码为字符串 const decodedStr = iconv.decode(buffer, charset); // 尝试转换为JSON对象 try { const fileList = JSON.parse(decodedStr); console.log('解析后的文件列表(JSON):', fileList); return; } catch (e) { // 不是JSON格式,按自定义分隔符解析 parseCustomFormat(decodedStr); } } function parseCustomFormat(str) { // 按行分割有效数据 const lines = str.split('\n').filter(line => line.trim()); const fileList = lines.map(line => { // 从每行提取账户和文件名(根据你的示例格式匹配) const account = line.match(/Account_(\d+)/)?.[1]; const filename = line.match(/(\d{4}-\d{2}-\d{2}\.csv)/)?.[1]; return { account, filename }; }); console.log('解析后的文件列表:', fileList); }
4. 数据类型说明
你拿到的是带自定义分隔符的二进制编码文本,乱码原因是:
- 要么数据被gzip/deflate压缩,未解压直接转字符串
- 要么服务端用了非UTF-8编码输出,Node.js默认用UTF-8解码导致乱码
通过以上步骤先解压(如果需要)、再用对应编码转码,最后根据实际格式解析为对象即可。
内容的提问来源于stack exchange,提问作者coldpumpkin
相关产品推荐
相关产品推荐

