无法从 Node 中的 http 请求正文解析数组

Cannot parse array from http request body in Node

我正在尝试在我的 node.js 路线中使用 application/x-www-form-urlencoded 编码的 POST 主体。

在命令行中使用 curl 请求:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'trx[0][trx_amt]=4166481.208338&trx[0][trx_crdr]=CR&trx[0][trx_tran_type]=TR&trx[0][trx_ref1]=5979NY270557&trx[1][trx_amt]=-5735967.281740&trx[1][trx_crdr]=DR&trx[1][trx_tran_type]=II&trx[1][trx_ref1]=7305XN175748' localhost:8080/api/test

我现在想解析这些值并将它们放入一个数组数组中(没有 key/value 对)。解析请求正文中的值工作正常,也将它们放入一个数组 (current_trx),但是将该数组作为一个元素推入另一个数组 (trx_data) 会使数组空白。请帮助我了解问题所在。

app.post("/api/test", (req, res) => {
 
  console.log(JSON.stringify(req.headers));
  console.log(req.body);

  var trx_data = [];
  var current_trx = [];

  for (let i = 0; i < req.body.trx.length; i++) {
    current_trx.push(parseFloat(req.body.trx[i].trx_amt));
    current_trx.push(req.body.trx[i].trx_crdr);
    current_trx.push(req.body.trx[i].trx_tran_type);
    current_trx.push(req.body.trx[i].trx_ref1);
    
    trx_data.push(current_trx); // this seems not to have any effect, trx_data remains empty
    
    console.log("CURRENT_TRX:");
    console.log(current_trx);  // this works fine, output as expected

    // emptying current_trx for the next loop
    while (current_trx.length > 0) {
      current_trx.pop();
    }
  }

  console.log("TRX_DATA ARRAY");  // empty..
  console.log(trx_data);

  res.sendStatus(200);

});

你可以用Array.map解决这个问题,

您正在向 trx_data 添加值并清空它。您可以在循环内移动 var current_trx = [];,这也将解决删除清除逻辑的问题。

app.post("/api/test", (req, res) => {
  const trx = req.body.trx;
  const trx_data = trx.map((item) => {
    const current_trx = [];
    current_trx.push(parseFloat(item.trx_amt));
    current_trx.push(item.trx_crdr);
    current_trx.push(item.trx_tran_type);
    current_trx.push(item.trx_ref1);
    return current_trx;
  });
  console.log(trx_data);
  res.sendStatus(200);
});