axios设置了responseType:arraybuffer,如何在只动接口代码的前提下返回json格式的数据?

const response = await axio.get({
      responseType: 'arraybuffer',
      url, 
      method: 'POST'
});
console.log(response.data); // 正常情况这里是返回buffer
console.log(response.data.data); // 现在期望这里能返回buffer

希望上述请求返回的response.data.data能接收到buffer,可以改接口,但不能改前端代码

尝试使用node实现了接口,返回json格式的数据,但没达到预期还是response.data是buffer,response.data.data是undefined

router.post('/a/b.zip', async ctx => {
  const filePath = path.join(__dirname, ctx.req.url.replace('/a', ''));

  const buf = fs.readFileSync(filePath);
  ctx.set('Content-Type', 'application/json');
  ctx.status = 200;
  ctx.body = {
          data: buf
     }
});
阅读 1.4k
2 个回答

如果你只希望这一个接口需要修改的话 直接

const response = await axio.get({
      responseType: 'arraybuffer',
      url, 
      method: 'POST'
}).then((respones) => ({ respones: { data: { data: respones.data } } }));
console.log(response.data); // 正常情况这里是返回buffer
console.log(response.data.data); // 现在期望这里能返回buffer

你需要所有 post responseType: 'arraybuffer', 那就重写 post 方法 给你一个思路。
const tempAxiosGet = axios.get;

axios.get = function <T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig<T>): Promise<R> {
  return tempAxiosGet<{ name: string }>(url, config)
    .then((respones) => ({ respones: { data: { data: respones.data } } }))
    .catch((error) => error)
}

利用 promise 的 then函数可以解决

你这个应该是无解了,你设置responseType是arraybuffer之后,无论你后端传的是文本还是json还是文件流,axios在response里都会以arraybuffer返回(会转),你这个只能动前端代码

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题