POST 期间控制台中的 FormData() 对象为空

FormData() object is empty in console during POST

这个问题以前有人问过,但我在另一个问题中找不到答案。当我记录我的表单数据时,我只得到 {} 我正在使用 fetch

从我的客户端 html 发送两个文本项和一个图像文件

我的表格

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

我在 chrome

的 XHR 预览中得到了什么
{}

我不确定为什么会这样,似乎根本没有获取表单值

不要将您的 FormData 字符串化,直接发送它,也不要设置请求 headers,让浏览器也处理它:

  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% 的情况下这就是您所需要的。