TL;DR
If you need file uploads, form-data
is your only option here. Otherwise, they serve the same job. form-data
is a fancier way of encoding data than x-www-form-urlencoded
. You can think of x-www-form-urlencoded
as .txt
file and form-data
as .html
file. In the end of day they both deliver some http payload.
Try 🏀 getd.io playground links 🏀 below to see what the headers and body look like:
Content Type
content-type | |
---|---|
x-www-form-urlencoded | application/x-www-form-urlencoded |
form-data | multipart/form-data; boundary={boundary string} |
A quick note for form-data
: Usually the browser generates a random {boundary string}
, e.g., ----WebKitFormBoundaryKGUmWkAsjo5nUBp2
, but you can specify your own if you want. See below for examples.
Request Payload
Let's say you have a login form with fields below:
Fields | Values |
---|---|
username | techbos |
password | Pa$$w0rd |
When you post the form, the payload for x-www-form-urlencoded
looks like below. Note how strings are encodeURIComponent()
'd.
username=techbos&password=Pa%24%24w0rd
For form-data
, each (key, value) pair is encoded in its own section, with {boundary string}
as separator. Here I also included a sample section in the end to show you what a file upload looks like:
--{boundary string} Content-Disposition: form-data; name="username", techbos --{boundary string} Content-Disposition: form-data; name="password", Pa$$w0rd --{boundary string} Content-Disposition: form-data; name="file"; filename="image.jpg" Content-Type: image/jpeg, --{boundary string}--
Explained inline:
API to send request
x-www-form-urlencoded | form-data | |
---|---|---|
fetch() | body as URLSearchParams | body as FormData |
request() | form option | formData option |
axios() | data as URLSearchParams | data as FormData |
API to handle response
For x-www-form-urlencoded
, use bodyParser, which will parse payload into req.body
in the format of { key, value }
.
express.use(bodyParser.urlencoded({ extended: true })); express.post('/my-form-endpoint', (req, res) => { console.log(req.body.username); // print 'techbos' });
Same functionality also comes built-in with Express v4.16.0+.
For parsing form-data
, you can use packages such as busboy or formidable. See their doc for how-to.
What's your favorite library for sending / handling forms? Leave a comment below to share your experience ❤️❤️❤️!
Check out getd.io and leave some feedback on what features you'd like to see next ❤️❤️❤️!
Top comments (6)
wow, thx!
Super useful! Thank you!
Hi, I am a user, I built a form through CKEditor, now how can get the data filled by users.
Thanks buddy
Thanks for Sharing
Thanks for the detailed info!