首页 >  文章 >  前端

Axios请求ArrayBuffer?教你轻松改成JSON返回!

时间:2025-03-07 10:51:03 151浏览 收藏

本文讲解如何解决Axios请求返回ArrayBuffer而非JSON数据的难题。 核心在于修改服务器端代码,而非客户端Axios配置。 通过将服务器端响应类型从`application/octet-stream`修改为`application/json`,并将ArrayBuffer数据转换为JSON可识别的格式(例如Base64编码),即可实现接口返回JSON数据。 文章以Node.js (Koa)框架为例,详细介绍了修改服务器端接口代码的步骤,并提供了完整的服务器端(Koa)和客户端(Axios)代码示例,帮助开发者快速解决问题。 无需修改客户端Axios代码,即可轻松解析JSON响应数据。

Axios请求返回arraybuffer,如何修改接口使其返回JSON数据?

如何修改Axios接口使其返回JSON数据而非ArrayBuffer

本文介绍如何修改后端接口,使其返回JSON数据,而不是使用Axios时返回的ArrayBuffer。假设您使用Axios发送GET请求并接收ArrayBuffer响应,但希望接口返回JSON格式的数据。 关键在于修改服务器端代码,而不是客户端Axios配置。

一、修改服务器端接口代码:

以下示例展示如何修改一个Node.js (koa) 后端接口,使其返回JSON数据:

原接口(返回ArrayBuffer):

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/octet-stream'); // or other appropriate content-type
  ctx.status = 200;
  ctx.body = buf; // Returns ArrayBuffer
});

修改后的接口(返回JSON):

router.post('/a/b.zip', async ctx => {
  const filepath = path.join(__dirname, ctx.req.url.replace('/a', ''));
  const buf = fs.readFileSync(filepath);
  // 将ArrayBuffer转换为可JSON化的格式 (例如Base64编码)
  const base64Data = buf.toString('base64'); 

  ctx.set('content-type', 'application/json');
  ctx.status = 200;
  ctx.body = JSON.stringify({ data: base64Data }); // Returns JSON
});

关键修改在于:

  1. ctx.set('content-type', 'application/octet-stream');改为ctx.set('content-type', 'application/json');
  2. ctx.body = buf;改为ctx.body = JSON.stringify({ data: base64Data });,其中base64Data是将buf转换为Base64编码后的字符串。 选择合适的编码方式取决于你的数据类型和需求。

二、客户端Axios代码 (无需修改):

因为我们修改了服务器端返回JSON,所以客户端Axios代码不需要更改responseType。 它会自动解析JSON响应。

三、完整示例 (Node.js Koa + Axios):

服务器端 (Koa):

const Koa = require('koa');
const Router = require('koa-router');
const fs = require('node:fs');
const path = require('node:path');

const app = new Koa();
const router = new Router();

router.post('/a/b.zip', async ctx => {
  const filepath = path.join(__dirname, ctx.req.url.replace('/a', ''));
  const buf = fs.readFileSync(filepath);
  const base64Data = buf.toString('base64'); 
  ctx.set('content-type', 'application/json');
  ctx.status = 200;
  ctx.body = JSON.stringify({ data: base64Data }); 
});

app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);

客户端 (Axios):

axios.post('/a/b.zip')
  .then(response => {
    console.log(response.data); // 解析JSON数据
    const decodedData = Buffer.from(response.data.data, 'base64'); // 解码Base64
    // ...处理decodedData...
  })
  .catch(error => {
    console.error(error);
  });

记住根据你的后端框架和数据类型调整代码。 例如,如果你使用的是Express.js,ctx将被替换成res。 你可能还需要调整Base64编码或使用其他编码方式,例如Uint8Array。 确保服务器端和客户端的编码方式一致。

到这里,我们也就讲完了《Axios请求ArrayBuffer?教你轻松改成JSON返回!》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>