You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Node.js返回的JSON格式Buffer在客户端转换为Blob

解决从JSON化的Buffer创建Blob的问题

咱们先梳理下问题里的代码问题,再一步步调整到正确的实现:

第一步:修复服务器端代码

你的Node.js代码里有两处小错误,会导致客户端拿不到正确的响应:

  1. 调用Buffer.toJSON()是错的,应该调用Buffer实例的toJSON()方法,也就是buffer.toJSON()
  2. res.json(response)里的response变量根本没定义,应该返回咱们处理好的jsonBuffer

修正后的服务器代码:

app.route('/api').post(async (req, res) => { 
  const buffer = Buffer.from('This is a test buffer');
  const jsonBuffer = buffer.toJSON(); // 调用实例方法获取JSON化的Buffer
  res.json(jsonBuffer); // 返回正确的JSON数据
});

第二步:客户端正确创建Blob

当服务器返回buffer.toJSON()的结果时,这个JSON对象的结构是{ type: 'Buffer', data: [字节数值数组] }。而Blob构造函数的第一个参数要求是包含二进制数据的可迭代集合(比如数组的数组、TypedArray等),直接传response.data是不符合要求的,得做个小包装。

方法一:直接包装数组

把字节数组放进一个数组里传给Blob,这是最简单的方式:

const rawResponse = await fetch('/api', { 
  method: 'POST', 
  headers: {"Content-type": "application/json; charset=UTF-8"}, 
  body: JSON.stringify('nothing') 
});
const response = await rawResponse.json();
// 把字节数组包裹在数组中,满足Blob构造函数的参数要求
const blob = new Blob([response.data], { type: 'text/plain' }); // 测试内容用text/plain更合适

方法二:转换成Uint8Array(更规范)

如果需要更严谨的二进制数据处理,可以把response.data转换成Uint8Array后再传入:

const rawResponse = await fetch('/api', { 
  method: 'POST', 
  headers: {"Content-type": "application/json; charset=UTF-8"}, 
  body: JSON.stringify('nothing') 
});
const response = await rawResponse.json();
const uint8Array = new Uint8Array(response.data);
const blob = new Blob([uint8Array], { type: 'text/plain' });

验证Blob内容(可选)

你可以用FileReader读取Blob内容,确认是否正确还原了原始字符串:

const reader = new FileReader();
reader.onload = () => {
  console.log('Blob内容:', reader.result); // 应该输出"This is a test buffer"
};
reader.readAsText(blob);

内容的提问来源于stack exchange,提问作者Cesar Morillas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 09:19:07