我正在制作一个基于评估通过 Multer 提供的文件缓冲区获得的文件签名的过滤器。我知道 Multer 提供了 MIME 类型,但我还必须通过其他一些验证方式来检查该文件是否实际上属于该 MIME 类型。
因此,我的步骤是:
问题是:一旦我在第二个端点上强制出现一些错误,该过程就会陷入循环。检测到错误,但是我无法返回任何 HTTP 代码作为对第一个端点的响应!
第一个端点:
/* NOTE: storeInMemory.array("files") stores in memory the files' buffer information, which
/* are needed in order to work with validating the files! */
app.post("/filesUpload", storeInMemory.array("files"), async (req, res) => {
const files = req.files;
/* this array stores the items i have to upload */
let uploadArray = [];
/* filter only the items i actually need to upload */
for (const item of files) {
/*-- some filter logic --*/
uploadArray.push(item);
}
/* create new FormData to store the actual files i have to upload -
/* as multer works with http a new formdata has to be created, so i can make a call to another endpoint */
let form = new FormData();
form.append("someData", req.body["someData"]);
/* append the files to the form i'll use to upload later */
uploadArray.forEach((item) => {
form.append("files", item.buffer, item.originalname);
});
try {
const postUrl = process.env.MY_URL + "/upload";
const myHeaders = { headers: { 'Content-Type': `multipart/form-data; boundary=${form._boundary}` } };
/* Request to other endpoint */
let uploadResult = await axios.post(postUrl, form, myHeaders);
if (uploadResult.status == 200) return res.send(uploadResult).status(200);
/* PROBLEM HERE: this is the point the program never gets to and i need it to */
else {
return res.send(uploadResult).status(500);
}
}
catch (error) {
console.error("Unpredicted error occurred: ", error);
return res.send(error)
}
});
第二个端点:
app.post("/upload", async (req, res) => {
try {
await new Promise((resolve, reject) => {
/* upload the files to cloud */
uploadOnCloud.array("files")(req, res, (err) => {
if (err) {
console.error("Error happened successfully!", err)
return reject(err);
}
else
return resolve();
});
});
/* If no err detected, ends with 200 */
res.sendStatus(200);
}
catch (error) {
/* PROBLEM: can neither set status, nor anything else */
res.status(500).send(error.message);
}
});
这里可能出了什么问题?
当您的第二个端点发送状态 500 时,您的第一个端点会假设发生了错误并直接转到您的
catch
。您需要在那里指定您的状态来解决您的问题:
catch (error) {
res.status(500).send(error.message);
}