提问人:Sushanth 提问时间:3/8/2023 更新时间:3/8/2023 访问量:50
如何等待响应直到产品图片上传到 GCP,因为在我收到 GCP 的响应之前,代码抛出 404 错误
How to await the response until the product image is uploaded to GCP, bacause now before I get the response from GCP, code is throwing 404 error
问:
我正在构建一个 nodejs 项目以将图像上传到 GCP 并将返回的字符串存储在 mongoDB 中,但在从 GCP 获取 reposne 之前,我收到 404 错误,然后它说 错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头
module.exports.addProductImage = async (request, response, next) => {
try {
const { color } = request.body;
const { id } = request.params;
if (!request.files?.images) {
return response.status(400).json({
status: false,
message: "No image provided",
data: null,
});
}
const imagesArr = await uploadMultipleImage(request.files.images, []);
if (!imagesArr) {
return response.status(400).json({
status: false,
message: "Error While Adding Product Image",
data: null,
});
}
const addProductQuantity = await Product.findOneAndUpdate(
{
_id: id,
},
{
$push: {
singleImage: {
color: color,
images: imagesArr[0],
},
images: {
color: color,
images: imagesArr,
},
},
},
{
new: true,
},
);
response.json({
status: true,
message: "Product Image Added Successfully",
data: addProductQuantity,
});
} catch (e) {
console.log("e", e);
return response.status(500).json({
status: false,
message: "Something went wrong. Please try again",
data: null,
});
}
};
这是 GCP 代码,我打算使用以下代码上传图像
const uploadFileToGCS = async (fileName, fileData) => {
return new Promise(async (resolve) => {
try {
const file = bucket.file(fileName);
const options = {
resumable: true,
// predefinedAcl: "publicRead",
};
await file
.save(fileData.data, options)
.then(() => {
resolve(true);
})
.catch((e) => {
resolve(false);
});
} catch (error) {
console.log("e",error)
resolve(false);
}
});
};
const uploadMultipleImage = async (images, oldArr) => {
return new Promise(async (resolve) => {
let fileArr = oldArr;
try {
await Promise.all(
images.map(async (element) => {
const fileName = `product/${new Date().getTime()}${path.extname(element.name)}`;
const Uploaded = await uploadFileToGCS(fileName, element);
console.log("%c Line:16 🍬 Uploaded", "color:#33a5ff", Uploaded);
if (Uploaded === false) {
resolve(false);
}
fileArr.push(fileName);
})
);
resolve(fileArr);
} catch (error) {
console.error(error);
resolve(false);
}
});
};
我正在尝试将图像上传到GCP,然后将返回的字符串存储在数据库中,但是我遇到了这个错误。
{ "success": false, "message": "404 Not Found" }
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
答: 暂无答案
评论
req.files
没有属性。我看到您正在尝试访问数据属性。您需要先流式传输文件,然后将它们转换为使用 Buffer 类型。您可能希望使用 Duplex 来处理它。data
Buffer