在express.js中传播运算符表单提交

可以传播运营商解决以下问题? 想象一下,我有更多的领域,那么我必须为每个领域声明req.body.something,这是非常乏味的。

app.use((res,req,next) => { const obj = { name: req.body.name, age: req.body.age, gender: req.body.gender } // User.saveUser(resp => res.json(resp)) //User model }) 

你可以使用解构赋值 :

 const obj = req.body; const { name, age, gender } = obj; 

但是,你仍然需要validation它,并把它们全部计入你的scheme中。

更新:

添加一些validation示例。
假设你的路线中有这样的模式:

 const tv4 = require('tv4'); const schema = { type: 'object', properties: { name: 'string', age: number, gender: { type: 'string', pattern: /f|m/i } }, required: ['name'] }; 

然后,在你的处理程序中,你validation:

 if (tv4.validate(req.body, schema) { // continue your logic here } else { // return 400 status here } 

你可以使用lodash的pick()

_.pick(对象,[path])

创build一个由拾取的对象属性组成的对象。

示例代码是:

 const _ = require('lodash'); ... const obj = _.pick(req.body, ['name', 'age', 'gender']); 

如果req.body中不存在gender ,它将被忽略 – 结果obj对象将不会有gender字段。


如果需要所有req.body字段,则可以将req.body分配给obj

 const obj = req.body; 

要validationreq.body内容,可以使用lodash的.has()

_.has(对象,path)

检查path是否是对象的直接属性。

示例代码将是:

 _.has(req.body, ['name', 'age', 'gender']); // return true if all fields exist. 

如果你不需要validation(在大多数情况下你可以这样做),你可以设置你的objvariables为req.body

 app.use((req, res, next) => { const obj = req.body; // User.saveUser(resp => res.json(resp)) //User model })