AJAX form with fetch() and Express


#1

I have a simple form

<form action="/userinfo" method="POST" name="userinfo">

<div><label for="name">name:</label><input name="name" type="text"></div>
<div><label for="age">age:</label><input name="age" type="text"></div>

<button type="submit">submit</button>
</form>

I am submitting it with fetch

    var form = document.forms['userinfo'];
    var formData = new FormData(form);
    function ajaxstuff(event) {
        event.preventDefault();

        fetch('/userinfo', {
            method: 'POST',
            body: formData
        })
    }
    form.addEventListener('submit', ajaxstuff);

I am logging in the command line with Express:

app.post('/userinfo', (req, res) => {
    console.log(req.body);
})

In the command line all i see is an empty object {}


#2

Found out I have to use a package called multer.

var multer = require('multer')
var upload = multer();

app.post('/userinfo', upload.single(), (req, res, next) => {
    console.log(req.body);
})

That is now displaying { name: '', age: '' } in the terminal even when the form is filled in.


#3

Hi @0llieW,

You need to create the FormData object inside ajaxstuff(), otherwise it's created when the page loads and the form is empty, which is why you don't get any values sent to the server.

function ajaxstuff(event) {
    event.preventDefault();

    var formData = new FormData(form);

    fetch('/userinfo', {
        method: 'POST',
        body: formData
    });
}

#4

Thanks, That worked!
I am curious to know what the benefit/difference is between using the FormData interface and using serialize(form) ?


#5

FormData can handle binary data (i.e file uploads), as it encodes the data as a multipart form.

Using something like jQuery's serialize method turns the data into a URL encoded string (e.g. name=Fred&age=30). You can't send files this way, but if you're only sending string data then it's more efficient (less overhead on the request).

There's some more detail on this SO post: https://stackoverflow.com/a/4073451/2411156


#6

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.