如何从多部分响应提取Notification对象并解决JSON解析错误?
解决获取multipart响应中Notification对象的问题
问题根源
你拿到的是multipart格式的响应,每个数据块用boundary分隔,还包含Content-Type、Content-Length这类头部信息。直接读取chunk解析JSON会把这些非JSON内容混进去,加上res.read()可能只读取部分JSON内容,自然会触发语法错误。
推荐解决方案:用multipart解析库(Busboy)
手动解析multipart格式容易出错,优先用成熟的库处理,以Node.js环境的busboy为例:
步骤1:安装依赖
npm install busboy
步骤2:修改请求代码
const Busboy = require('busboy'); const fetch = require('node-fetch'); // 根据你实际使用的HTTP客户端调整 // 注意原代码的Headers要改成小写headers,这是常见错误 var options = { method: method, body: body, headers: { "Content-Type": "application/json" }, }; const response = await fetch(URL, options); // 从响应头获取boundary,传给Busboy const busboy = new Busboy({ headers: response.headers }); // 监听每个multipart数据块 busboy.on('file', (_, file) => { let contentBuffer = []; // 收集数据块内容 file.on('data', chunk => contentBuffer.push(chunk)); // 数据块读取完成后解析JSON file.on('end', () => { const content = Buffer.concat(contentBuffer).toString('utf8'); try { const jsonData = JSON.parse(content); // 筛选出包含Notification的对象 if (jsonData.Notification) { console.log('目标Notification对象:', jsonData.Notification); // 这里添加你的业务逻辑 } } catch (err) { console.error('JSON解析失败:', err); } }); }); // 所有数据块处理完成的回调 busboy.on('finish', () => { console.log('响应处理完成'); }); // 将响应流导入Busboy处理 response.body.pipe(busboy);
备选方案:手动解析(不推荐,适合小体积响应)
如果不想用第三方库,可以手动分割响应内容,步骤如下:
const fetch = require('node-fetch'); var options = { method: method, body: body, headers: { "Content-Type": "application/json" }, }; const response = await fetch(URL, options); // 从响应头提取boundary const contentType = response.headers.get('content-type'); const boundary = contentType.split('boundary=')[1]; // 读取完整响应内容(仅适合内容不大的情况) const fullResponse = await response.text(); // 分割成单个数据块,过滤空内容 const parts = fullResponse.split(`--${boundary}`).filter(part => part.trim() !== ''); // 遍历每个数据块 for (const part of parts) { // 分割头部和JSON内容(空行是分隔符) const [_, content] = part.split('\r\n\r\n'); if (!content) continue; try { const jsonData = JSON.parse(content.trim()); if (jsonData.Notification) { console.log('找到Notification:', jsonData.Notification); // 处理你的逻辑 } } catch (err) { console.error('解析失败:', err); } }
注意事项
- 原代码中
Headers拼写错误,应该是小写的headers,这会导致请求头设置失效,务必修正。 - 手动解析仅适合小体积响应,大文件场景下会占用过多内存,优先用库处理。
内容的提问来源于stack exchange,提问作者jhon estrada
相关产品推荐
相关产品推荐

