7

I'm using node.js to receive a post request, the request body has this content after printing it using console.log():

{ 
  'object 1': 
   { 
     deviceType: 'iPad Retina',
     guid: 'DF1121F9-FE66-4772-BE74-42936F1357FF',
     is_deleted: '0',
     last_modified: '1970-12-19T06:01:17.171',
     name: 'test1',
     projectDescription: '',
     sync_status: '1',
     userName: 'testUser' 
   },
  'object 0': 
   { 
     deviceType: 'iPad Retina',
     guid: '18460A72-2190-4375-9F4F-5324B2FCCE0F',
     is_deleted: '0',
     last_modified: '1970-12-19T06:01:17.171',
     name: 'test2',
     projectDescription: '',
     sync_status: '1',
     userName: 'testUser' 
   } 
}

I'm getting the request using the below node.js code:

var restify = require('restify'),
    mongoose = require('mongoose');
var connect = require('connect');
var bodyParser = require('body-parser');
/*server declaration
...
...
*/
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));

server.post('/project', function (req, res, next) {
       console.log(req.body);//the output is shown above
       console.log(req.body.length);// --> output is undefined

       //2
       body.req.forEach(function (item) {//got an exception 
       console.log(item);
   });
});

The second part of the code which has forEach function gives this exception "[TypeError: Object #<Object> has no method 'forEach']"

Do you know what am I missing?

zoma.saf
  • 558
  • 3
  • 6
  • 14
  • 1
    possible duplicate of [Loop through JavaScript object](http://stackoverflow.com/questions/684672/loop-through-javascript-object) – Anurag Peshne Feb 27 '15 at 12:30

3 Answers3

16

req.body isn't an array, but an object with two properties. This is evident from the console.log output you've provided. Therefore, it has no length property and no forEach method.

If it had been an array, it would have looked like this:

[ 
   { 
     deviceType: 'iPad Retina',
     guid: 'DF1121F9-FE66-4772-BE74-42936F1357FF',
     is_deleted: '0',
     last_modified: '1970-12-19T06:01:17.171',
     name: 'test1',
     projectDescription: '',
     sync_status: '1',
     userName: 'testUser' 
   },
   { 
     deviceType: 'iPad Retina',
     guid: '18460A72-2190-4375-9F4F-5324B2FCCE0F',
     is_deleted: '0',
     last_modified: '1970-12-19T06:01:17.171',
     name: 'test2',
     projectDescription: '',
     sync_status: '1',
     userName: 'testUser' 
   } 
]

To iterate over the keys of the object you have, you can use the construct

for(var key in req.body) {
  if(req.body.hasOwnProperty(key)){
    //do something with e.g. req.body[key]
  }
}
Peter Herdenborg
  • 5,736
  • 1
  • 20
  • 21
  • Thank you for the info. I'm still a beginner in node.js and this info will help. You saved my day! – zoma.saf Feb 27 '15 at 12:23
  • Note if you get "req.body.hasOwnProperty is not a function" you need to `JSON.parse(JSON.stringify(req.body));` https://github.com/expressjs/express/issues/3264 to ensure its based on an Object – scipilot Oct 05 '18 at 10:03
12

forEach is defined only for Arrays.

You need to use for...in loop instead:

for (var key in req.body) {
  if (req.body.hasOwnProperty(key)) {
    item = req.body[key];
    console.log(item);
  }
}
zoma.saf
  • 558
  • 3
  • 6
  • 14
Anurag Peshne
  • 1,547
  • 12
  • 29
1

I use JS object, it works fast and for sure. Also I re-use Object.keys for email/DB row/column names. This is working website (professorMiriam.com/donate) code:

      app.post('/donate', (req, res) => {  
    let nm1=req.body.name1,nm2=req.body.name2;
    let frm={
    'Name':nm1 +' '+ nm2,
    'Email':req.body.email,
    'Date':req.body.dt,
    'Endorse':req.body.rcmmnd,
    'Note':req.body.note,
    'ip':req.body.ip,
    'Amount':req.body.mnt,
    'Often':req.body.often};
    
     for(const key of Object.keys(frm)) {if(frm[key].length<1){frm[key]='N/A';}}

//simplicity to add email just in 2!! lines:
let strng=JSON.stringify(frm); strng=strng.replace(/","/g,'<br>').replace(/":"/g,': ').replace('{"','').replace('"}','<br>END');    
var mail={from:'steve@websystem.us',to:[USR,USRF],subject:usd,html:strng};