DEV Community

Send data to a node.js server with FormData, a comprehensive guide.

Karin on March 11, 2024

There are many different ways to send data from an HTML form to a server. I wanted to provide a deep dive into using the FormData JavaScript interf...
Collapse
 
fyodorio profile image
Fyodor

Cool to see that, this topic is quite underpaid with attention in our SPA world 🙂

Collapse
 
khenhey profile image
Karin

Thanks!

Collapse
 
sc1entifik profile image
Sc1entifik

The thing you didn't mention here that I can't seem to find ANYWHERE going elbow deep into documentations and tutorials is this:

How do I

e.preventDefault()
Enter fullscreen mode Exit fullscreen mode

for a form submission, then add data to the form via form.append so I can add extra data that is not user submitted to the form, and then submit that form so I can access that data on my node server AND then redirect the user to another page?

For example if I don't

e.preventDefault()
Enter fullscreen mode Exit fullscreen mode

and go the urlencoded() route my page will get redirected from the server side using

res.sendFile(some.html)
Enter fullscreen mode Exit fullscreen mode

without me being able to add extra key:value pairs to the form such as

form.append("postKey","passphrase");
Enter fullscreen mode Exit fullscreen mode

but once I

e.preventDefault()
Enter fullscreen mode Exit fullscreen mode

I can create, and send a FormData object, adding the extra fields I want to it such as

form.append("postKey","passphrase");
Enter fullscreen mode Exit fullscreen mode

, using a fetch request. Once this Content-Type header is no longer the form default however how do I then use something like res.sendFile() server side to then redirect the user? When I try to do this using either mulitpart form OR json I just run into a brick wall. I can access all the data server side and make conditionals using the request body however when I try to use

res.sendFile(some.html);
Enter fullscreen mode Exit fullscreen mode

to redirect the user I get no errors and nothing happens.