【发布时间】:2021-07-09 00:27:01
【问题描述】:
我正在尝试从客户端删除图像,但销毁方法不起作用,不会删除图像,同时也没有给我任何错误。
我正在使用 React.js,这是我的方法:
deleteProductHandler = id => {
db.collection("products")
.doc(id)
.delete()
.then(() => {
// update the UI
const products = [...this.state.products];
let images = [];
products.forEach((product, index) => {
if (product.id === id) {
products.splice(index, 1);
images = [...product.images];
this.setState({ show: false, products: products });
}
});
// delete images from cloudinary
let links = images
.map(link => {
return link.match("products/");
})
.map(link => {
const newlink = link.input.slice(link.index);
const newlink2 = newlink.slice(0, -4);
return { publicId: newlink2 };
});
let publicIds = [];
for (let key in links) {
publicIds.push(links[key].publicId);
}
console.log(publicIds);
// i got all publicIds here without any problem.
// so dont wory about the code above.
publicIds.forEach(publicId => {
console.log(publicId);
window.cloudinary.v2.uploader().destroy(publicId, (err, res) => {
console.log(err, res);
});
});
})
.catch(err => {
this.setState({ error: err });
});
};
这是destroy方法的文档: https://cloudinary.com/documentation/image_upload_api_reference#destroy_method
我想在这里说明的是,当用户删除一个产品时,它的图像会自动从 cloudinary 中删除。
【问题讨论】:
-
您如何为 Cloudinary API 提供身份验证?除了在某些情况下支持未签名上传的上传 API 的显着例外,您通常不能在 React 等客户端代码中使用该 API(因为在客户端代码中没有安全的方法来创建签名,并且如果您'正在进行服务器端调用以从您的后端获取签名,您的后端也可以直接调用 Cloudinary API)
-
另外,您是否在浏览器的网络选项卡中看到对 API 的请求?是否有响应被发送但没有出现在你的 React 代码中,或者实际上没有调用?
-
据我所知,destroy 方法不需要签名,它会自动生成,在我的情况下,它是未签名的上传。
-
根本没有打电话。
-
destroy方法当然需要认证,认证是基于SDK使用你账户的API secret生成的签名,不能直接在客户端代码中使用。也就是说,如果没有发出 HTTP 请求,则第一个问题可能出在 Javascript 代码本身中,如果解决了,您将看到身份验证错误。一般来说,如果您尝试在前端代码中从 NodeJS SDK 调用方法,由于缺少依赖项,它可能无法正常工作,但我希望某处会显示错误 - 您在控制台?
标签: javascript reactjs cloudinary