简体   繁体   中英

formdata object is empty for html form post request

I'm trying to use formdata object to send form data to my server. I need this because one of my input fields is a file. However the formdata object is blank when I try to send the data to my server, it also prints out "{}". What is the issue? I have jquery updated to 11.1 which supports formdata. Thanks.

  <form enctype="multipart/form-data" name="formName" id="formId">
    <input type="text" name="name" class="form-control" id="name">
  </form>
  <button type="submit" class="btn btn-xl sub">Send Message</button>

  <script>
      $(".sub").click(function(){
         var formElement = document.querySelector("form");
         alert(formElement); //alert message is "[object HTMLFormElement]"
         var d = new FormData(formElement);
         alert(JSON.stringify(d)); //alert message is "{}"
         $.post("/email",d,function(data){
            alert("success!");
         });
      });
  </script>

Server:

/*never reaches endpoint*/
app.post('/email', function(req, res) {
    console.log("entered");
    console.log(req.body) // form fields
    console.log(req.files) // form files
    var resume = req.files;
    email(req.body, resume);
});

https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

How are you parsing the body of POST requests on your node server?

The issue is that FormData will set the content type to be multipart/form-data , which Express' body-parser doesn't understand.

Note the comment here :

[body-parser] does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules: busboy and connect-busboy; multiparty and connect-multiparty; formidable; multer.

So in other words, you have to user a different module to handle the multipart body that FormData sends. I can recommend formidable , in which case you're server code would look something like:

const formidable = require('formidable')

exports.createPost = (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, (err, fields, files) => {
        console.log(fields)
        res.send('NOT IMPLEMENTED: pollsController createPost');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM