Объект FormData () пуст в консоли во время POST - PullRequest
0 голосов
/ 29 мая 2020

этот вопрос задавался раньше, но я не смог найти ответ в другом вопросе. когда я регистрирую свои данные формы, я просто получаю {} я отправляю два текстовых элемента и один файл изображения от моего клиента html с помощью fetch

моя форма

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

функция постданных

 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
}

отправка запроса с объектом формы

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

то, что я получаю в моем предварительном просмотре XHR в chrome

{}

Я не уверен, почему это происходит, просто кажется, что значения формы вообще не захватываются

1 Ответ

1 голос
/ 29 мая 2020

Не привязывайте свои FormData к строкам, отправляйте их напрямую и не устанавливайте заголовки запросов, позвольте браузеру обрабатывать и это тоже:

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

И обратите внимание, что вам не нужно, и вероятно, даже не следует устанавливать все параметры выборки, просто используйте значения по умолчанию, в 99% случаев это то, что вам нужно.

...