How do you extract POST data in Node.js?
Older Article
This article was published 8 years ago. Some information may be outdated or no longer applicable.
When you’re building Node.js web apps, you’ll eventually need to grab data from a form submission. Here’s how to pull POST data out of a request.
The setup
We’re going to use Express v5 (still in alpha at the time of writing). Install it: npm install express@5.0.0-alpha.2 --save
Curious about what changed between Express v4 and v5? Read this article.
body-parser
body-parser is an npm plugin for Express that lets you capture form data. Express used to ship with this baked in, but it got pulled out into its own package for easier maintenance.
Install it: npm install body-parser --save
Creating the application
With both packages installed, create an index.html file and a simple HTTP server called 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'));
The HTML sets up a <form> that posts data to the /api/data endpoint. Nothing fancy.
In app.js, we wire up body-parser and tell Express to use it.
The
urlencoded()method requires a parameter. It returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option.
The urlencoded() method creates a new body object on the request property. This object holds key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).
Fire up the app with node app.js, open a browser at http://localhost:3000, and submit some data. You’ll see the form field’s name attribute as the key in your console and whatever you typed as the value.