使用 Axios/Sharp 下载图像并调整其大小

Downloading and resizing an image with Axios/Sharp

我目前正在尝试使用 Axios 下载图像,然后调整结果大小并通过 GraphQL 解析器中的 Node 将其保存在本地。

这是我正在使用的代码块:

axios.get(url)
    .then((response) => {
        const { set, collector_number } = response.data;
        const sourceUrl = response.data.image_uris.border_crop;
        const filename = `${set}/${collector_number}.png`;
        axios.get(sourceUrl, { responseType: 'arraybuffer' })
            .then((res) => {
                console.log(`Resizing Image!`)
                sharp(res)
                    .resize(226, 321)
                    .toFile(`../cardimg/${filename}`)
                    .then(() => {
                        console.log(`Image downloaded and resized!`)
                    })
                    .catch((err) => {
                        console.log(`Couldn't process: ${err}`);
                    })
            })
    })

当我执行代码时(通过 GraphQL Mutation),它会抛出一条错误消息:Input file is missing.

不知道是Axios的误用,还是我用的Sharp有问题

有什么建议吗?我最初担心我需要弄乱来自 HTTP 请求的响应格式,但据我所知,我做对了。

提前致谢!

我已经使用console.log来确保它肯定是在抓取图像并且URL是正确的,所以已经测试过了,所以sourceUrl确实在抓取图像,我是只是不确定如何正确地使用我正在抓取的数据做任何事情。

axios returns 完整响应正文,如 statusheadersconfig。响应正文在 .data 键中。所以在你的情况下它将是:

axios.get(..).then((res) => { sharp(res.data)})

此外,Promises inside promises 被认为是反模式,您可以轻松地将其链接起来。

let fileName;
axios.get(url)
  .then((response) => {
    const { set, collector_number } = response.data;
    const sourceUrl = response.data.image_uris.border_crop;
    filename = `${set}/${collector_number}.png`;
    return axios.get(sourceUrl, { responseType: 'arraybuffer' })
  })
  .then((res) => {
    console.log(`Resizing Image!`)
    return sharp(res.data)
      .resize(226, 321)
      .toFile(`../cardimg/${filename}`)
  })
  .then(() => {
    console.log(`Image downloaded and resized!`)
  })
  .catch((err) => {
    console.log(`Couldn't process: ${err}`);
  })