Search code examples
javascriptfetchform-data

FormData() object is empty in console during POST


this question has been asked before but I couldn't find the answer in another question. when I log my formdata I just get {} i am sending two items that are text and one image file from my client html using fetch

my form

 <form id="addform">

      <div class="form-group">
        <label for="exampleInputPassword1">post</label>
        <input type="text" class="form-control" id="title" placeholder="article title">
        <textarea type="text" class="form-control bigbox" id="body" placeholder=""></textarea>

        <input type="file" id="image" placeholder="image" name="imageFile">
      </div>

      <button id="addpost" type="submit"class="btn btn-primary">add Post</button>
    </form>

postdata function

 async function postData(url = '', data) {

  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'no-cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default , no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      //'Content-Type': 'application/json'
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

sending the request with a form object

document.getElementById("addpost").addEventListener('click',function(e){
      e.preventDefault()
      let form = document.getElementById('addform')
      let formdata = new FormData(form)
      formdata.append('title',document.getElementById("title").value)
      formdata.append('body',document.getElementById("body").value)
      formdata.append('imageFile',document.getElementById("image").files[0])    

      postData(`http://${window.location.hostname}:3000/admin/addpost`,formdata)
      .then((data)=>{console.log(data.data)})
    })

what i get in my XHR preview in chrome

{}

I'm not sure why this is happening it just seems to not be grabbing the form values at all


Solution

  • Don't stringify your FormData, send it directly, and don't set the request headers, let the browser handle that too:

      const response = await fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'no-cors', // you probably don't want this... let the default "cors"
        cache: 'no-cache', // not sure why you'd want that either...
        credentials: 'same-origin', // include, *same-origin, omit
    // removed the Headers, the browser knows how to talk to a server, that's hos job.
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: data // pass directly the FormData here
      });
    

    And note that you don't have to, and probably even shouldn't set all the options of the fetch, just use the defaults, in 99% of cases that's what you need.