Mis*_*olf 1 node.js 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}`);
})
})
})
Run Code Online (Sandbox Code Playgroud)
当我执行代码(通过 GraphQL Mutation)时,它会抛出一个错误,指出:Input file is missing。
不确定这是 Axios 的误用,还是我对 Sharp 的操作有问题。
有什么建议么?我最初担心我需要弄乱来自 HTTP 请求的响应的格式,但从我收集到的信息来看,我做得正确。
提前致谢!
我已经使用 console.log 来确保它确实抓取了图像并且 URL 是正确的,因此已经经过测试,因此 sourceUrl 确实抓取了图像,我只是不确定如何正确执行任何操作 -with-我正在抓取的数据。
axios返回完整的响应正文,例如status, headers, config。响应正文是.data关键。所以在你的情况下它将是:
axios.get(..).then((res) => { sharp(res.data)})
Run Code Online (Sandbox Code Playgroud)
此外,承诺内的承诺被认为是反模式,您可以轻松链接它。
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}`);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4408 次 |
| 最近记录: |