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

如何在Strapi中强制Koa输出指定格式的Buffer响应

解决Koa中直接输出Buffer的JSON表示问题

问题原因分析

  • 把Buffer包裹在对象中赋值给ctx.body时,Koa会自动序列化整个对象,返回包含data字段的嵌套结构。
  • 直接将Buffer赋值给ctx.body且设置Content-Type: application/octet-stream时,Koa会输出Buffer的二进制原始内容,也就是转成字符串"test"。

实现方案

要直接输出{type:"Buffer", data:[...]}格式的响应,需要手动处理Buffer的序列化:

  1. 调用Buffer实例的toJSON()方法,获取其标准JSON表示对象;
  2. 将该对象转成JSON字符串后赋值给ctx.body;
  3. 根据内容格式设置Content-Type为application/json(让浏览器识别为JSON格式),同时保留下载头配置。

示例代码

const fooFunction = async (ctx: Context) => {
  const buffer = Buffer.from("test");
  // 获取Buffer的JSON结构对象
  const bufferJson = buffer.toJSON();
  // 转为JSON字符串作为响应体(第三个参数用于格式化输出,可选)
  ctx.body = JSON.stringify(bufferJson, null, 2);
  // 设置响应头
  ctx.response.set("Content-Type", "application/json");
  ctx.response.set(
    "Content-disposition",
    `attachment;filename=foo.bar`
  );
  return ctx;
};

预期响应

{
  "type": "Buffer",
  "data": [116, 101, 115, 116]
}

如果需要保持Content-Type: application/octet-stream(仅影响浏览器识别方式,不改变内容),只需修改对应的响应头即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:28:25