0

So I am appending additional data to FormData:

 async submit(el, codes = null) {
        try {
            const formData = new FormData(el);

            if (codes) {
                for (let i = 0; i < codes.length; i++) {
                    formData.append('codes[]', codes[i]);
                }
            }

            const response = await http({
                method: el.method,
                url: el.action,
                data: formData,
            });
    }
}

But this is what I get:

[2021-09-01 08:56:57] local.INFO: array (
  'email' => 'email@gmail.com',
  'password' => 'password',
  'codes' => 
  array (
    0 => '[object Object]',
  ),
)  

And how it should be:

[2021-09-01 09:00:18] local.INFO: array (
  'email' => 'email@gmail.com',
  'password' => 'password',
  'codes' => 
  array (
    0 => 
    array (
      'code' => 'test2',
      'puk' => 'DH58LEJV',
    ),
  ),
)  

How should I fix this?

zyyyzzz
  • 220
  • 2
  • 11
  • 1
    That might just be a quirk of the console output. – evolutionxbox Sep 01 '21 at 09:03
  • 1
    Does this answer your question? [How can I get the full object in Node.js's console.log(), rather than '\[Object\]'?](https://stackoverflow.com/questions/10729276/how-can-i-get-the-full-object-in-node-jss-console-log-rather-than-object) – evolutionxbox Sep 01 '21 at 09:04
  • 1
    Nope, it doesnt do what it is supposed to do with ```codes``` data. – zyyyzzz Sep 01 '21 at 09:04
  • see if this helps: https://stackoverflow.com/questions/53735223/js-how-to-append-array-in-formdata – J_K Sep 01 '21 at 09:35

1 Answers1

0

The append() function takes a key/value pair. So the value should be a string or number etc. In your case it looks like an object because object.toString() will return "[object Object]". So, maybe you should just stringify the object:

var codes = [{
  code: 'test1',
  puk: 'DH58LEJV'
}, {
  code: 'test2',
  puk: 'DH58LEJV'
}];

document.forms.form01.addEventListener('submit', e => {
  e.preventDefault();
  let formData = new FormData(e.target);
  codes.forEach(code => {
    formData.append('codes[]', JSON.stringify(code));
  });

  fetch(e.target.action, {
      method: e.target.method,
      body: formData
    })
    .then(res => res.text())
    .then(text => console.log(text));
});
<form name="form01" method="POST" action="data:text/plain;base64,dGVzdA==">
  <input type="text" name="email" value="text@example.org" />
  <input type="password" name="password" value="1234" />
  <button>Send</button>
</form>
chrwahl
  • 8,675
  • 2
  • 20
  • 30