如何从req.body取回数组?

时间:2018-12-23 07:01:06

标签: javascript node.js

我正在将对象数组发送到Node.js服务器。在req.body上收到消息后,我得到了一个带有单个键的Object,它包含了数组中的所有对象。

我尝试了几种方法,例如迭代对象,它返回单个键。也尝试过JSON.parse(),但它已经是一个字符串。

与string.split(“,”)一样,但它看起来复杂且效率低。

/* Sent from client */
var names = [{
    "firstName" : "Darshak",
    "lastName" : "Mehta"
  },{
    "firstName" : "Russell",
    "lastName" : "Peters"
  }];


/* Obtained following at server in req.body */ 
const y = { '{"firstName":"Darshak","lastName":"Mehta"},
{"firstName" : "Russell","lastName" : "Peters"}': '' }

编辑

客户

await this.add([{
    "firstName" : "Darshak",
    "lastName" : "Mehta"
  },{
    "firstName" : "Russell",
    "lastName" : "Peters"
  }]);

add = (data) => {
    var config = {
      headers: {
         'Content-Type': 'application/x-www-form-urlencoded',
      }
 };
    axios.post('http://localhost:8080/data', data, config)
      .then((res) => {
        /* Successful message */
      })
      .catch((err) =>{
        console.log(err);
      });
  };

服务器

const bodyParser = require('body-parser');
const express = require('express');
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const app = express();

app.post('/data', urlencodedParser, async (req, res) => {
    console.log(typeof Object.keys(req.body)[0]); /* Outputs String */
    console.log(req.body);
});

我正在尝试找回名称数组。

2 个答案:

答案 0 :(得分:1)

在发送之前更新数据对象

Scanner.nextInt()

CLIENT

现在从req.body获取userArray
await this.add([{ "firstName": "Darshak", "lastName": "Mehta" }, { "firstName": "Russell", "lastName": "Peters" }]); add = (data) => { var config = { headers: { 'Content-Type': 'application/json', } }; var userArray = { userArray: data }; axios.post('http://localhost:8080/data', userArray, config) .then((res) => { /* Successful message */ }) .catch((err) => { console.log(err); }); };

server

答案 1 :(得分:0)

此对象未正确序列化/字符串化。在此请求字符串中,只有一个键({“ firstName”:“ Darshak”,“ lastName”:“ Mehta”}, {“ firstName”:“ Russell”,“ lastName”:“ Peters”}),其值为空字符串。这应该在请求系统中解决。它应该已经像这样被序列化了:

"[{"firstName":"Darshak","lastName":"Mehta"},
{"firstName" : "Russell","lastName" : "Peters"}]"