【问题标题】:Using axios with Node to get a picture jpg使用axios配合Node获取图片jpg
【发布时间】:2021-05-18 00:53:23
【问题描述】:

我正在尝试使用 axios 从另一个 Node 应用程序 [通过 Node http get request] 获取图片。 问题是,当我使用 axios 时,我得到了错误的文件格式,当我保存它时,它没有 看看石灰一张图片...当我使用http get时,我得到了一张完美的图片,并且保存得很好。

  • 获取图片的工作代码:

接收方:

    var data = new Stream.Transform();
    res.on('data', function(chunk) {
        console.log(typeof chunk)
        data.push(chunk);
    });

    res.on('end', function() {
      fs.writeFileSync('event.png', data.read());
    });

发件人:

export const getImage =  (req, res) => {
const pathToImage = 'C:/dev/server/images/event.jpg';
const img = fs.readFileSync(pathToImage);

res.writeHead(200, {'Content-Type': 'blob' });
res.end(img, 'binary');
}
  • axios(无效代码):
axios.get(url)
    .then((response: AxiosResponse)=>{
          // save picture locally:
          let data = new Stream.Transform();
          data.push(response.data);
          fs.writeFileSync('event.jpg', data.read());
     })
     .catch((error: AxiosError) => {
         console.log(error.message);
     })

你知道为什么 axios 不像 http 那样工作吗?

【问题讨论】:

  • 可以用邮递员获取图片吗?
  • 是的,正如我所说,我可以使用简单的 http get 获取它。

标签: node.js axios http-get node-rest-client


【解决方案1】:

知道了——很简单:

const response = await axios({
        url,
        method: 'GET',
        responseType: 'stream'
    })
    fs.writeFileSync('event.png', response.data.read());

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 2021-06-10
    • 2018-10-11
    • 2020-11-20
    • 2020-09-01
    • 1970-01-01
    • 2011-04-01
    • 2021-04-12
    • 1970-01-01
    相关资源
    最近更新 更多