简体   繁体   中英

Failing gracefully if any json data is missing in Node.JS post request

I am trying to set up a post request on a node.js server such that if any data from the json report is missing it just throws an error rather than doing anything with the database.

My server is a mongodb server using express and body-parser. Here is the code I want to create

app.post('/update', function(req, res) {
  const params = req.body;

  const newData = {
    id: params.id,
    data: params.data
    .../a ton more data
  };

  if (anything is missing from newData (any field is undefined) ) {
   res.send({err: true});
  } else {
   //Some cool database things
  }

}

I realize that I could just check if any of my fields are undefined however that is not really elegant especially when I am about to have about 20 fields in the incoming data.

You can create a JSON schema for your request and then validate your actual request with the existing JSON schema using npm package like ajv

You can checkout more about JSON schema from here . You can create your own JSON schema from here .

there is a module in node JS called JOI which does the initial payload validation.

And for using this with express JS check express-joi Express Joi Link

var express = require('express');
var expressJoi = require('express-joi');

var Joi = expressJoi.Joi; // The exposed Joi object used to create schemas and custom types 

var app = express();
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
app.use(errorHandler);

// Use the Joi object to create a few schemas for your routes.  
var getUsersSchema = {
  limit: expressJoi.Joi.types.Number().integer().min(1).max(25),
  offset: expressJoi.Joi.types.Number().integer().min(0).max(25),
  name: expressJoi.Joi.types.String().alphanum().min(2).max(25)
};

var updateUserSchema = {
  userId: Joi.types.String().alphanum().min(10).max(20),
  name: Joi.types.String().min(3).max(50)
};
// Attach the validator to the route definitions 
app.get('/users', expressJoi.joiValidate(getUsersSchema), handleUsers);
app.put('/users/:userId', expressJoi.joiValidate(updateUserSchema), 
 handleUpdateUser);

app.listen(8080);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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