spread operator form submission in express.js


Can spread operator solve below problem? Imagine I have more fields, then I have to declare req.body.something for every single fields, that’s so tedious.

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


You can use destructuring assignment:

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

But, still you will have to validate it, and count all of them in your scheme.


Adding some validation example.
Assuming such schema in your route:

const tv4 = require('tv4');

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

And then, in your handler you validate:

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

Answered By – Lazyexpert

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published