我正在努力将文件上传到S3,一切正常,但在为multer设置错误处理时遇到了一些问题。
我的表单发布路径以前是这样的(
listController.list__post
// routes.js
const singleUpload = upload.array("image", 3);
router.post('/list-product', singleUpload, listController.list__post)
看完文件,,
https://github.com/expressjs/multer#error-handling
,我对我的代码做了这些更改,它只在处理multer错误时起作用
// routes.js
router.post("/list-product", function (req, res, next) {
singleUpload(req, res, function (err) {
if (err instanceof multer.MulterError) {
console.log("error 1");
res.render("list", {
form: req.body,
imgErr:
"Please make sure your images are JPG or PNG, and less than 1024 MB each",
});
return;
} else if (err) {
console.log("error 2");
return;
}
// Everything went fine.
});
});
listController.list\u post
router.post("/list-product", listController.list__post, function (req, res, next) {
即使每个字段都填写了正确的信息,express验证器也会为每个字段返回错误。
我的express验证程序代码:
// listController.js
exports.list__post = [
body("productName")
.trim()
.isLength({ min: 1 })
.withMessage("Please enter the name of your product"),
body("productPrice").isNumeric().withMessage("Please enter a valid price"),
body("productCategory")
.trim()
.isLength({ min: 1 })
.withMessage("Please select the category of your product"),
body("productDescription")
.trim()
.isLength({ min: 50 })
.withMessage("Please enter a product discription (minimum 50 characters)")
.isLength({ max: 150 })
.withMessage("Maximum 300 characters"),
body("businessName")
.trim()
.isLength({ min: 1 })
.withMessage("Please enter the name of your business"),
body("website")
.trim()
.isURL()
.withMessage("Please enter the URL for your product or business"),
// body('image')
// im going to set up a custom validation
// here so that I won't have to rely
// on multer's validation, multer will
// just be a backup/extra security
sanitizeBody("*").escape(),
(req, res, next) => {
const errors = validationResult(req);
let errArray = errors.array();
if (!errors.isEmpty()) {
console.log(errors);
res.render("list", {
form: req.body,
errors: errArray,
msg: "Please check the form for errors",
option: req.body.productCategory,
});
return;
} else {
let product = new Product({
business: req.body.businessName,
productName: req.body.productName,
category: req.body.productCategory,
price: req.body.productPrice,
description: req.body.productDescription,
website: req.body.website,
imageURL:
"https://mybucket.s3-us-west-2.amazonaws.com/" + req.imageName,
imageURL2:
"https://mybucket.s3-us-west-2.amazonaws.com/" + req.imageName,
});
product.save(function (err) {
if (err) {
console.log(err);
return next(err);
}
res.redirect("/list-product");
});
}
},
];
请让我知道,如果我可以提供任何更多的信息或背景,谢谢期待!