Home > Blockchain >  How to fix validate request with NodeJs?
How to fix validate request with NodeJs?

Time:08-25

I have a controller that can validate every data before save into the database, but i do not know what happend with it when i test on postman. Every time when i try to test my api, i let some data is empty but my server gonna crash. Can anyone explain to me what's wrong with my validate and give me some advice or suggestion.

// 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,
        });
      });
  }

CodePudding user response:

This is not the right way to validate data coming to your server!
You should validate data with some kind of validator and there are many libraries for that.
Take for example: express-validator

CodePudding user response:

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;
      }
  • Related