快速验证器的验证不适用于中间件

问题描述 投票:0回答:1

我正在尝试在后端创建一家餐厅,一切看起来都是正确的,但是当我在创建餐厅路线时通过验证中间件时,即使我按照应有的方式填写了每个字段,它也会被解雇

餐厅管理员:

const createRestaurant = async (req: Request, res: Response) => {
  try {
    const existingRestaurant = await Restaurant.findOne({
      user: req.userId,
    });

    if (existingRestaurant) {
      return res.status(409).json({ message: "User already has a restaurant" });
    }

    const image = req.file as Express.Multer.File;
    const base64Image = Buffer.from(image.buffer).toString("base64");
    const dataURI = `data:${image.mimetype};base64,${base64Image}`;

    const uploadResponse = await cloudinary.v2.uploader.upload(dataURI);

    const restaurant = new Restaurant(req.body);
    restaurant.imageUrl = uploadResponse.url;
    restaurant.user = new mongoose.Types.ObjectId(req.userId);
    restaurant.lastUpdated = new Date();
    await restaurant.save();

    res.status(201).send(restaurant)
  } catch (error) {
    console.log(error);
    res.status(500).json({ message: "Something is wrong" });
  }
};

验证.ts:

export const validateRestaurant = [
    body("restaurantName").notEmpty().withMessage("Restaurant name is required"),
    body("city").notEmpty().withMessage("City is required"),
    body("country").notEmpty().withMessage("Country is required"),
    body("deliveryPrice")
      .isFloat({ min: 0 })
      .withMessage("Delivery price must be a positive number"),
    body("estimatedDeliveryTime")
      .isInt({ min: 0 })
      .withMessage("Estimated delivery time must be a postivie integar"),
    body("cuisines")
      .isArray()
      .withMessage("Cuisines must be an array")
      .not()
      .isEmpty()
      .withMessage("Cuisines array cannot be empty"),
    body("menuItems").isArray().withMessage("Menu items must be an array"),
    body("menuItems.*.name").notEmpty().withMessage("Menu item name is required"),
    body("menuItems.*.price")
      .isFloat({ min: 0 })
      .withMessage("Menu item price is required and must be a postive number"),
    handleValidationErrors,
  ];

餐厅路线:


router.post(
  "/",
  validateRestaurant,
  jwtCheck,
  jwtParse,
  upload.single("imageFile"),
  createRestaurant
);

餐厅模式:

import mongoose from "mongoose";

const menuItemSchema = new mongoose.Schema({
  name: { type: String, required: true },
  price: { type: Number, required: true },
});

const restaurantSchema = new mongoose.Schema({
  user: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
  restaurantName: { type: String, required: true },
  city: { type: String, required: true },
  country: { type: String, required: true },
  deliveryPrice: { type: Number, required: true },
  estimatedDeliveryTime: { type: Number, required: true },
  cuisines: [{ type: String, required: true }],
  menuItems: [menuItemSchema],
  imageUrl: { type: String, required: true },
  lastUpdated: { type: Date, required: true },
});

export const Restaurant = mongoose.model("Restaurant", restaurantSchema);

错误:enter image description here在每个字段中,通过传递每个字段似乎都会触发此错误

我想快速解决这个问题,这样我就可以在前端工作并制作我的项目

node.js express backend mern express-validator
1个回答
0
投票

我知道问题是什么了:

我试图在后端从 multer 上传文件之前进行验证,现在当我进行更改时,我可以创建餐厅

正确代码:

    router.post(
  "/",
  upload.single("imageFile"),
  validateRestaurant,
  jwtCheck,
  jwtParse,
  createRestaurant
);
© www.soinside.com 2019 - 2024. All rights reserved.