0

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,
        });
      });
  }
2
  • 1
    Add a return after each status 400 to not execute further code on error Commented Aug 25, 2022 at 8:22
  • Exactly you should use a package to validate data. It will be useful for you. Commented Aug 27, 2022 at 8:08

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

So, what i have to do to validate my req.body.name. Could you post some example on here
-1
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;
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.