3

I've this code for login. When I debug the code, I check that the FormData() constructor does not return anything, it is empty. What am I doing wrong? The formLog constant does collect the form data but after passing it to the FormData() constructor, the returned object is empty

<form id="login" method="post" enctype="multipart/form-data" name="login">
    <input type="email" name="email" placeholder="Tu email">
    <br><br>
    <input type="password" name="password" placeholder="Tu contraseña">
    <br><br>
    <input type="submit" value="Login">
</form>

<script type="text/javascript">
    const formLog = document.querySelector('#login')
    //Creamos un objeto con los datos del formulario

    // AL formLog le agregamos un evento 
    formLog.addEventListener('submit',event =>{
        event.preventDefault()
        const data = new FormData(formLog)       
        fetch('/api/signin',{
            method:'POST',
            body: data,
        })
        .then(res => {
            res.json()
        })
        .then(resData => {
            localStorage.setItem('token', resData.token)
        })
    })
</script>
  • Use [this](https://developer.mozilla.org/en-US/docs/Web/API/FormData/values#Example) and you will see that `data` does indeed contain the form data. You can also check the XHR params in the console, and it will also show the names and values. –  Jan 22 '19 at 00:08

1 Answers1

-1

Using spread syntax will get all the values from your FormData object. Then use Array#reduce and destructuring to organize everything within a simple object.

const form = document.getElementById("login");

form.addEventListener("submit", function(e){
  e.preventDefault();
  
  const data = [...new FormData(this)]
  .reduce((a,[key,value])=>{
    a[key] = value;
    return a;
  }, {});
  
  console.log(data);
});
<form id="login" method="post" enctype="multipart/form-data" name="login">
    <input type="email" name="email" placeholder="Tu email" value="test@test.com">
    <br><br>
    <input type="password" name="password" placeholder="Tu contraseña" value="some password">
    <br><br>
    <input type="submit" value="Login">
</form>
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131