expressjs accept post data form

How to Access POST Form Fields in ExpressJS

ExpressJS is one of the most popular NodeJS modules for building websites and applications using NodeJS frameworks. It provides tons of functions to easily accept data from client side, process it and send back responses. In this article, we will learn how to access POST form fields in ExpressJS. This is a problems faced by many beginner NodeJS developers, especially since ExpressJS keeps changing the steps from one version to the next.

How to Access POST Form Fields in ExpressJS

Depending on ExpressJS version you are using, you need to change the initialization part to correctly process request data.

If you are using ExpressJS 4.0 to 4.15, then you need to install body-parser module first.

$ npm install --save body-parser

Then add the following lines to your NodeJS server code. We have assumed that you have already imported ExpressJS into your code and that your application is denoted by app variable.

var express = require('express');
var app = express();
var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 

If you are using ExpressJS < 3.0 or 4.16+ then you can directly call the body parsers from expressJS without installing body-parser module.

var express = require('express');
var app = express();
app.use(express.json());       // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies

Once you have initialized the body parsers in ExpressJS, you can define the POST request handler in app.post() function. In this function, we define a function to accept request data and process it. It takes two arguments – request and response object. The first argument is the request object, mentioned as req variable. It receives request data as a JS object of key-value pairs.

app.post('/test-page', function(req, res) {
    var name = req.body.name,
        color = req.body.color;
    // ...
});

For example, if your POST request has one of the following formats.

// assuming POST: name=foo&color=red            <-- URL encoding
//
// or       POST: {"name":"foo","color":"blue"}  <-- JSON encoding

Then you will be able to access POST data variables name and color as req.body.name and req.body.color respectively.

In this article, we have learnt how to access POST form fields in ExpressJS. The key is to use the appropriate data parsers depending on ExpressJS version, and access request data as JS objects.

Also read:

How to Detect Scroll Direction in JavaScript
How to Split String With Multiple Delimiters in JS
How to Split String With Multiple Delimiters in Python
How to Clone Array in JavaScript
How to Check MySQL Storage Engine Type

Leave a Reply

Your email address will not be published. Required fields are marked *