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 } });

阅读量:15

点赞量:0

问AI
如果你只希望这一个接口需要修改的话 直接 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 >(url: string, config?: AxiosRequestConfig): Promise { return tempAxiosGet(url, config) .then((respones) => ({ respones: { data: { data: respones.data } } })) .catch((error) => error) } 利用 promise 的 then函数可以解决