Explain Codes LogoExplain Codes Logo

How to access POST form fields in Express

javascript
express
middleware
form-data
Alex KataevbyAlex Kataev·Jan 3, 2025
TLDR

Use Express's built-in express.urlencoded() middleware to parse form data as follows:

const express = require('express'); const app = express(); // This little chunk of code will save your day app.use(express.urlencoded({ extended: true })); app.post('/submit-form', (req, res) => { // it's like peeking into Pandora's box, without all the evils res.send(`Form field value: ${req.body.yourFieldName}`); }); app.listen(3000);

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 multiparty or busboy for 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 using req.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:

app.post('/submit-form', (req, res) => { let data = ''; req.on('data', chunk => { data += chunk; }); req.on('end', () => { // The magic happens here }); });

Mind the middleware order

Jigsaw puzzle, anyone? Middleware should be placed before your routes – just like having your socks on before shoes.

app.use(express.urlencoded({ extended: true })); // Now mom will be happy, as all routes below will have 'req.body' available and parsed app.post('/submit-form', (req, res) => { ... });

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 } in express.urlencoded() and see them prettify.
  • Files refuse to line up for the upload? You're going to need a multipart/form-data parser.

Parsing per content type

For the moments when you need to cater to different audiences or content types:

app.post('/submit-form', (req, res, next) => { if (req.is('json')) { // JSON? Cool, I got this! app.use(express.json()); } else if (req.is('urlencoded')) { // You said URL-encoded? Roger that! app.use(express.urlencoded({ extended: true })); } next(); });