【问题标题】:Error: 'name' is required. on post request from postman using form data错误:“名称”是必需的。根据邮递员使用表单数据的发布请求
【发布时间】:2021-06-03 04:18:29
【问题描述】:

.required() 函数用于节点 js 的 post 请求中的名称、价格、数量。如果我删除所需的功能,那么它可以正常工作。 模型文件代码:

var productSchema = mongoose.Schema({
  name: String,
  price: Number,
  quantity: Number,
});
var Product = mongoose.model("Product", productSchema);

function validateProduct(data) {
  const schema = Joi.object({
    name: Joi.string().min(3).required(),
    price: Joi.number().min(0).required(),
    quantity: Joi.number().min(0).required(),
  });

api文件代码

router.post(
      "/",
      validateProduct,
      upload.single("productImage"),
      async (req, res) => {
        console.log(req.file);
        let product = await Product.findOne({ name: req.body.name });
        if (product)
          return res.status(400).send("Product with same name already exist!");
        product = new Product();
        product.name = req.body.name;
        product.price = req.body.price;
        product.quantity = req.body.quantity;
        await product.save();
        return res.send(product);
      }
    );

【问题讨论】:

  • 尝试console.log() req.body 看看它有什么。您是否正确解析表单数据?
  • 你是否包含了validateProduct函数的完整代码?如果你把它用作中间件,我认为在某个地方一定有schema.validate & next()
  • 是的,我有。 return schema.validate(data, { abortEarly: false });

标签: node.js postman


【解决方案1】:

我看到了一些问题:

  • 首先,您在 POST "/" 路由中使用 validateProduct 作为中间件。所以,函数应该有(req, res, next) 作为参数。我不确定为什么当您在 JOI 模式中删除所需的函数时它可以工作。在我的测试中,我将其重写为:
function validateProduct(req, res, next) {
     
    // to check the value of req.body
    console.log(req.body);

     // create schema object
    const schema = Joi.object({
        name: Joi.string().min(3).required(),
        price: Joi.number().min(0).required(),
        quantity: Joi.number().min(0).required(),
    }).required();

    // schema options
    const options = {
        abortEarly: false, // include all errors
        allowUnknown: true, // ignore unknown props
        stripUnknown: true // remove unknown props
    };

    // validate request body against schema
    const { error, value } = schema.validate(req.body, options);

    if (error) {
        // on validate failed
        req.validationError = true;
        next();
    } else {
        // on success replace req.body with validated value and trigger next middleware function
        req.body = value;
        next();
    }
}
  • 其次,在调用 upload 中间件之前,req.body 未完全填充。您需要将validateProduct 中间件放在upload 之后。 (我在上面的validateProduct函数中添加了console.log(body),你可以看到两种情况的区别。)
app.post(
    "/",
    upload.single("productImage"),
    validateProduct,
    async (req, res) => {
        console.log(req.file);

        if (req.validationError) {
            // validation failed
            fs.unlinkSync(req.file.path); // need require("fs") at the top of file
            return res.status(400).send("Parameters is not valid!");
        }


        let product = await Product.findOne({ name: req.body.name });
        if (product) {
            return res.status(400).send("Product with same name already exist!");
        }
        product = new Product();
        product.name = req.body.name;
        product.price = req.body.price;
        product.quantity = req.body.quantity;
        await product.save();
        return res.send(product);
    }
);
  • 最后(可选),因为我们在验证其他字段之前已经上传了文件,如果不满足要求,我们需要删除文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 2020-02-28
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多