Avoid error of validating json input

I’m getting this error only when I send invalid form of json request
how do i validate the user input if it’s a valid json ?

	<pre>SyntaxError: Unexpected token u in JSON at position 7<br> &nbsp; &nbsp;at JSON.parse (&lt;anonymous&gt;)<br> &nbsp; &nbsp;at parse (C:\Users\midoe\Desktop\competetion\node_modules\body-parser\lib\types\json.js:89:19)<br> &nbsp; &nbsp;at C:\Users\midoe\Desktop\competetion\node_modules\body-parser\lib\read.js:121:18<br> &nbsp; &nbsp;at invokeCallback (C:\Users\midoe\Desktop\competetion\node_modules\raw-body\index.js:224:16)<br> &nbsp; &nbsp;at done (C:\Users\midoe\Desktop\competetion\node_modules\raw-body\index.js:213:7)<br> &nbsp; &nbsp;at IncomingMessage.onEnd (C:\Users\midoe\Desktop\competetion\node_modules\raw-body\index.js:273:7)<br> &nbsp; &nbsp;at IncomingMessage.emit (events.js:327:22)<br> &nbsp; &nbsp;at endReadableNT (_stream_readable.js:1220:12)<br> &nbsp; &nbsp;at processTicksAndRejections (internal/process/task_queues.js:84:21)</pre>
  createUser: (req, res) => {
    const validate = createUser_schema.validate(req.body)
    if (validate.error){
      return res.status(400).json({
        success: 0,
        message: validate.error.details[0].message
      })
    }
    const body = req.body
    const salt = genSaltSync(10);
    body.password = hashSync(body.password, salt);
    create(body, (err, results) => {
      if (err) {
        console.log(err)
        return res.status(500).json({
          success: 0,
          message: "Database error",
          reason: err.sqlMessage
        })
      }
      if (results) {
        return res.status(200).json({
          success: 1,
          message: {name: body.name, email: body.email}
        })
      }
    })
  }

1 possible answer(s) on “Avoid error of validating json input

  1. This should also work to handle errors thrown from express.json()

    app.use(express.json());
    app.use(function(err, req, res, next) {
      // handle err
    });