How to access POST form fields in Express
Use Express's built-in express.urlencoded() middleware to parse form data as follows:
Ensure to replace yourFieldName with the actual name of your form's input field. After this setup, server-side will be able to retrieve form values sent to /submit-form direct from req.body.
Decode the form encoding types
Forms could be submitted using various encoding types, most common being application/x-www-form-urlencoded and multipart/form-data. It's like understanding whether your gift is wrapped in a paper or a box.
- For URL-encoded forms which are typically text data, middleware setting as shown above works perfectly.
- File uploads are typically sent as multipart/form-data which would require third-party modules like
multipartyorbusboyfor parsing more conveniently and securely.
Don't forget security guards
When it comes to user inputs, security can't take a back seat. So always remember to:
- Include
express.json()middleware for accepting JSON data. - Consider
{ extended: true }for URL-encoded parsing only when nested objects and arrays are expected in the payload. - Abstain from deprecated methods such as
req.param(). Make sure you call your date up directly usingreq.body.fieldName. - If accepting file upload, cling onto secure libraries and ditch the idea of using
express.multipart(), as it's shirt is ragged.
Custom parser rule!
For those bespoke scenarios needing custom parsing, or maybe some non-standard content-types, you can skip the courier and deliver the message yourself:
Mind the middleware order
Jigsaw puzzle, anyone? Middleware should be placed before your routes – just like having your socks on before shoes.
Common hiccups & fixes
Encountering issues is part of the process. Here are some you might bump into and how to fix them:
- Is your form data not being parsed? Make sure your middleware is lined up before your routes.
- Nested objects coming out unsightly? Set
{ extended: true }inexpress.urlencoded()and see them prettify. - Files refuse to line up for the upload? You're going to need a
multipart/form-dataparser.
Parsing per content type
For the moments when you need to cater to different audiences or content types:
Was this article helpful?