【问题标题】:NodeJS Axios request returning an odd stringNodeJS Axios 请求返回一个奇怪的字符串
【发布时间】:2023-04-05 20:25:01
【问题描述】:

我正在向第三方 API 发送一个 GET 请求,它返回一个奇怪的字符串(应该是一个图像)。

axios.get(`${URL}/test`, {
    headers: {
        'Content-Type': 'application/json',
    },
    auth: {
        username: USERNAME,
        password: PASSWORD
    },
    responseType: 'blob'
})
.then(async (response) => {
    console.log(response.data)
    return res.json(response.data);
})
.catch((err) => {
    console.log(err);
    return res.json("ERROR");
});

响应是: "����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000C

如何将其转换为图片或图片/网址?

谢谢

【问题讨论】:

  • 你试过responseType: 'json'responseType: 'text'吗?
  • 我刚试过。响应是一样的
  • 哦,对不起,我看错了。如果是图片,应该是responseType: 'arraybuffer'或者responseType: 'stream',因为不是json,使用res.json没有意义。您可以按照答案或​​使用fs.writeFile(filePath, Buffer.from(data, encoding))保存文件。
  • 谢谢。我不想保存它,我想获取 base64 图像并将其发送回我的 React 应用程序,我将在我的网站上显示图像

标签: node.js axios blob


【解决方案1】:

你可以试试这个

const Fs = require('fs')  
const Path = require('path')  
const Axios = require('axios')

async function downloadImage () {  
  const url = 'https://unsplash.com/photos/AaEQmoufHLk/download?force=true'
  const path = Path.resolve(__dirname, 'images', 'code.jpg')
  const writer = Fs.createWriteStream(path)

  const response = await Axios({
    url,
    method: 'GET',
    responseType: 'stream'
  })

  response.data.pipe(writer)

  return new Promise((resolve, reject) => {
    writer.on('finish', () => { /* Add your code here */ resolve(); })
    writer.on('error', () => { /* Add your code here */ reject(); })
  })
}

downloadImage()  

【讨论】:

    猜你喜欢
    • 2020-03-23
    • 2022-09-27
    • 2014-02-28
    • 2013-03-05
    • 2019-01-07
    • 2021-02-17
    • 2019-11-14
    • 2020-05-07
    • 2020-01-15
    相关资源
    最近更新 更多