简体   繁体   English

如果Node.JS发布请求中缺少json数据,则正常失败

[英]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. 我试图在node.js服务器上设置一个发布请求,这样,如果json报告中的任何数据丢失,它只会引发错误,而不是对数据库做任何事情。

My server is a mongodb server using express and body-parser. 我的服务器是使用express和body-parser的mongodb服务器。 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. 我意识到我可以检查是否有未定义的字段,但这并不是很优雅,特别是当我即将在输入数据中包含约20个字段时。

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 您可以为您的请求创建一个JSON模式,然后使用ajv等npm包使用现有的JSON模式验证您的实际请求

You can checkout more about JSON schema from here . 您可以从此处查看有关JSON模式的更多信息。 You can create your own JSON schema from here . 您可以从此处创建自己的JSON模式。

there is a module in node JS called JOI which does the initial payload validation. 节点JS中有一个称为JOI的模块,它会进行初始有效负载验证。

And for using this with express JS check express-joi Express Joi Link 并与Express JS一起使用时请检查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);

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

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