Often times when working with Node.js based web applications we are faced with an option to handle data sent from a form. In this article we'll take a look at how to extract POST data in Node.js.
In this example we are going to use Express v5 (which is at alpha release at the time of writing this article), so let's go ahead and install it: npm install express@5.0.0-alpha.2 --save
If you're curious to see the changes between Express v4 and v5 please read this article.
body-parser is an npm plugin for Express that we need to use in order to be able to capture data coming via a form. Express used to have this functionality built-in but in order to achieve easier maintenance body-parser has been removed from the core of Express.
In order to use body-parser we need to install it: npm install body-parser --save
Once the installation is complete we can create an index.html
file and a simple HTTP web server, let's call that app.js
.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Express - Node.js POST data example</title>
</head>
<body>
<form action="/api/data" method="POST">
Some data: <input type="text" name="data" id="data" />
<button type="submit">Send</button>
</form>
</body>
</html>
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (request, response) =>
response.sendFile(`${__dirname}/index.html`)
);
app.post('/api/data', (request, response) => {
const postBody = request.body;
console.log(postBody);
});
app.listen(3000, () => console.info('Application running on port 3000'));
These two files are very straight forward. The HTML creates a <form>
element that has an action
attribute that posts data to the /api/data
endpoint.
In app.js
we are using body-parser and we are telling our Express application to use that plugin as well.
The
urlencoded()
method requires us to pass in a parameter. This method returns a middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option.
It is this plugin, via the urlencoded()
method that creates a new body object which we can access on the request
property. This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).
We can test this by firing up our application via node app.js
and opening a browser and navigating to http://localhost:3000
. By sending some data via the application we should see the name
attribute as the key in our console and the actual data as the property.