0

I am trying to consume an application/x-www-form-urlencoded encoded POST body in my node.js route.

Request using curl on the command line:

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

I now want to parse those values and put them into an array of arrays (no key/value pairs). Parsing the values from the request body works fine, putting them into an array as well (current_trx), but pushing that array as an element into another array (trx_data) leaves the array blank. Please help me understand what the problem is.

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

});

1 Answer 1

1

You can use Array.map to solve this,

You are adding values to trx_data and emptying the same. you can move var current_trx = []; inside loop, which will also solve the issue is removed clearing logic.

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Moving var current_trx = [] inside the loop and removing the pop function solved the problem. However, I don't understand why.. current_trx is populated in each loop, then pushed to trx_data and then the content of current_trxis removed, not the content of trx_data. Hence I am not sure why the trx_data is empty.. I haven't removed any values from it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.