繁体   English   中英

如何使用 NodeJs 修复验证请求?

[英]How to fix validate request with NodeJs?

我有一个 controller 可以在保存到数据库之前验证每个数据,但是当我在 postman 上测试时,我不知道它发生了什么。 每次我尝试测试我的 api 时,我都会让一些数据为空,但我的服务器会崩溃。 任何人都可以向我解释我的验证有什么问题并给我一些建议或建议。

// create new car
export async function createCar (req, res) {
   // My validate request
    if (!req.body.name) {
        res.status(400).send({
          message: "Name can not be empty!"
        });
        //return;
      } else if (!req.body.color){
        res.status(400).send({
            message: "Color can not be empty!"
        });
      } else if (!req.body.brand) {
        res.status(400).send({
            message: "Brand can not be empty!"
        });
        //return;
      }
    // Every time i try to empty some data, my server gonna crash. i need a suggestions for this //issue
    const car = new Car({
      car_id: id,
      name: req.body.name,
      color: req.body.color,
      brand: req.body.brand,
    });
    
    return car
      .save()
      .then((newCar) => {
        return res.status(201).json({
          success: true,
          message: 'New car created successfully',
          Car: newCar,
        });
      })
      .catch((error) => {
          console.log(error);
        res.status(500).json({
          success: false,
          message: 'Server error. Please try again.',
          error: error.message,
        });
      });
  }

这不是验证传入服务器的数据的正确方法!
您应该使用某种验证器来验证数据,并且有很多库可以做到这一点。
举个例子: express-validator

if (!req.body.name) {
        res.status(400).send({
          message: "Name can not be empty!"
        });
        return;
      } else if (!req.body.color){
        res.status(400).send({
            message: "Color can not be empty!"
        });
        return;
      } else if (!req.body.brand) {
        res.status(400).send({
            message: "Brand can not be empty!"
        });
        return;
      }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM