首页 > 解决方案 > 如何在 React 中将 arrayBuffer 转换为 JSON

问题描述

我正在使用 Axios,我得到arraybuffer了回应。我想转换arraybufferjson. 我真的很努力,但没有找到合适的解决方案。有人可以帮助我。

谢谢

axios.post(
  `${config.apiPath}/api/generatepdf`,
  {
    onlyForPdf: 'pdf',
  },
  {
    responseType: 'arraybuffer',
    headers: {
      Accept: 'application/pdf',
    },
  }
).then((res) => {
  console.log('2@ res', JSON.parse(new TextDecoder().decode([res.data])))
}

在控制台中它返回未定义

标签: javascriptreactjsecmascript-6arraybuffer

解决方案


使用以下语法切换回 JSON。

let arrayBufferConverted = JSON.parse(
 String.fromCharCode.apply(null, new Uint8Array(res.data))
   )

推荐阅读