req.files 返回无法读取未定义的属性(读取“0”)

req.files returning Cannot read properties of undefined (reading '0')

我正在使用 multer 存储并且它工作正常但是当输入字段为空时这里的错误它一直发送 “文件已上传” ,我想在什么时候做请求文件未定义或为空它returns“字段为空”除此之外它检查它是图像还是pdf文件

const uploadFiles = async (req, res) => {

try {
    
    await upload(req, res);
    console.log(req.files);
  
    if (req.files == undefined) {
        return res.send({message : "Fields is Empty"})
    }
    if (req.files !== undefined) {
        if (req.files.bookCover[0].fieldname == "bookCover" && req.files.bookCover[0].bucketName != 'photos' ) {
            return res.send({ message: "Please Upload an Image" })
        }
        if (req.files.bookFile[0].fieldname == "bookFile" && req.files.bookFile[0].bucketName != 'pdf') {
            return res.send({ message: "Please Upload a PDF File" })
        }
    }
    res.send({ message : "File has been uploaded. "})
} catch (error) {
    console.log(error);
    return res.send({ message : "Error Uploading the File !"})
}

}

它一直给我这个错误无法读取未定义的属性(读取'0')所以我将它们包装在另一个if语句中如果字段不是未定义它检查它是否是一个已上传图片或 pdf 文件

但它不起作用

这是我对@CherryDT 所做的修复

try{
    await upload(req, res);
    console.log(req.files);
    if (!req.files.bookCover ) {
        return res.send({ message: "Book Cover is Empty" });
    } else if (!req.files.bookFile) {
        return res.send({ message: "Book File is Empty" });
    }
    else {
    if (req.files.bookCover?.[0].fieldname == "bookCover" && req.files.bookCover?.[0].bucketName != 'photos' ) {
        return res.send({ message: "Please Upload an Image" })
    }
    if (req.files.bookFile?.[0].fieldname == "bookFile" && req.files.bookFile?.[0].bucketName != 'pdf' ) {
        return res.send({ message: "Please Upload a PDF File" })
        }
    }
    res.send({ message: "File has been uploaded. " })
}
 catch (error) {
    console.log(error);
    return res.send({ message : "Error Uploading the File !"})
}