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

图片代理API使用Axios返回损坏图片,请求代码排查

问题分析与解决

你的代码里存在一个关键问题:axios返回的response.data是ArrayBuffer类型,而Node.js的res.write()方法直接处理ArrayBuffer并指定'binary'编码时,会导致数据解析错误,最终生成的图片文件损坏无法显示。

修复方案

将ArrayBuffer转换为Node.js原生的Buffer类型后再发送给客户端,同时可以简化响应头的设置方式:

router.get("/queue", (req, res) =>  {
  axios({
    method: 'GET',
    url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/2560px-Image_created_with_a_mobile_phone.png',
    responseType: 'arraybuffer'
  }).then(function(response) {
    // 将ArrayBuffer转换为Node.js Buffer
    const imageBuffer = Buffer.from(response.data);
    // 设置响应头并发送图片数据
    res.setHeader('Content-Type', 'image/png');
    res.send(imageBuffer);
  }).catch(function(error) {
    // 返回500错误状态码及错误信息
    res.status(500).send("error:" + error.message);
  });
});

额外优化说明

  • 使用res.setHeader()替代res.writeHead(),更符合Express框架的常用写法,代码更简洁
  • 错误处理时返回500状态码,符合HTTP错误响应规范
  • 捕获错误时使用error.message,避免直接拼接Error对象可能引发的异常

修改后重新运行curl命令或访问API地址,生成的图片就能正常显示了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:02:17