当前位置: 代码网 > it编程>网页制作>html5 > Axios请求返回arraybuffer,如何修改接口使其返回JSON数据?

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

2025年03月30日 html5 我要评论
如何修改axios接口使其返回json数据而非arraybuffer本文介绍如何修改后端接口,使其返回json数据,而不是使用axios时返回的arraybuffer。假设您使用axios发送get请

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数据?的详细内容,更多请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com