node.js - req.body 不能作为数组读取

标签 node.js

我正在使用 node.js 接收发布请求,请求正文在使用 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' 
   } 
}

我正在使用以下 node.js 代码获取请求:

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);
   });
});

代码的第二部分有 forEach函数给出了这个异常“[TypeError: Object #<Object> has no method 'forEach']

你知道我错过了什么吗?

最佳答案

req.body 不是数组,而是具有两个属性的对象。从您提供的 console.log 输出中可以明显看出这一点。因此,它没有 length 属性,也没有 forEach 方法。

如果它是一个数组,它应该是这样的:

[ 
   { 
     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' 
   } 
]

要遍历您拥有的对象的键,您可以使用构造

for(var key in req.body) {
  if(req.body.hasOwnProperty(key)){
    //do something with e.g. req.body[key]
  }
}

关于node.js - req.body 不能作为数组读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28764822/

相关文章:

node.js - sinon - 创建返回自己参数的 stub

javascript - Mocha + typescript : Cannot use import statement outside a module

javascript - 当我在 expressjs 中使用 req.param 并在我的后 Controller 中使用 nodejs 时,我得到 UNDEFINED

node.js - 如何在 WSL 2 Ubuntu 中更新 npm

javascript - 在 npm 包中传递 init 值

javascript - WebStorm IDE 文件监视 CoffeeScript 创建一个空文件

node.js - Nodemailer 和 postfix

node.js - 使用 Node js和socket-io向WebRTC中的许多观众广播(一对多广播)

node.js - 在 XLSX 导出期间在工作表的开头插入新行/注释

javascript - 等待 JavaScript 返回 API 结果