Getting Data From req.body in Node.js & Express Server | WM
A Node.js and Express server can receive data from a client in many ways. Typically when a user sends a POST request also sends some data in the request body. The server needs to extract that information from the request body.
The body-parser
package is used to get data from the request body in an Express server. After setting up this package as a middleware function, it will extract information passed by a user and store it in the req.body
object. Any route can access the data from that object.
From the client side, a user submits a form that sends a POST request with the information from the form inputs. They can also use other HTTP clients like Axios or the fetch()
method in JavaScript to send data to the server.
Build REST API Using Node.js, Expre…
Please enable JavaScript
Build REST API Using Node.js, Express and MongoDB
In this lesson, you will learn how to extract those data from the request and access it through the req.body
object inside a Node.js and Express server.
You can also use URL query strings and parameters in Express to get information from users to your server. But you have to follow techniques to extract them.
Install body-parser Package to Get Data From req.body
To use the body-parser
package, you need to have an Express server. If you don’t have the server, you can follow our best setup guide for an Express server with TypeScript.
Now, you need to install this package inside your project. You can install this package using the following command:
npm install body-parser
You can use it after the installation by importing this package into your project. Let’s see how to apply it as a middleware function and get data in Express.
How to Get Data From Request Body in Express
The body-parser
package parsers the JSON, raw buffer data, plain text, and URL-encoded data like x-www-form-urlencoded
content type.
Most of the time, we parse JSON and URL-encoded data in our servers. For that, you have to use two methods from this package to handle these two types of data.
For JSON data:
app.use(bodyParser.json());
This json()
method will parse any type of JSON data from the request body in the Express server. If you know that your server will only get data in a JSON format from the users, you will use this method.
If the client uses the fetch()
API or Axios to send the request, they set the content-type
header as application/json
because they send data in JSON format.
For URL-encoded data:
app.use(bodyParser.urlencoded({ extended: false }));
If the users send POST requests by submitting a form, it will use application/x-www-form-urlencoded
as the content-type
to send the data. To parse that from the request body, we need to use the urlencoded()
method.
With the extended option, you can choose between the query-string
library or the qs
library to parse the URL-encoded data. You can set this option as true
or false
.
Note: The
query-string
library can not create a nasted object from the data. But theqs
library can create a nested object.
If it is set to false then the urlencoded()
method will use the query-string
library. When the extended
is true, this method will use the qs
library. You can choose any one of them.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Home page');
});
app.post('/login', (req, res) => {
console.log(req.body.email);
console.log(req.body.password);
// validate email and password here
res.redirect('/dashboard');
});
app.get('/dashboard', (req, res) => {
res.send('Dashboard page');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`server listening on ${PORT}`);
});
I am getting the package and using both urlencoded()
and json()
methods so that I can parse JSON and URL-encoded data in my server.
Now I will be able to access any data from the request body using the req.body
object. In this example, I have a POST /login
route where a user will send email
and password
to log in.
I will get those data from the req.body
and validate the data. If the information is correct, it will redirect to another route using the Express res.redirect()
method.
Now you know why and how we get data from the request body in the Express server.
Conclusion
As you know, we can use URL query strings and parameters to transfer data from a client to the server. But it has a limited capacity. To exchange a large amount of data between the client and server, we use the POST method.
To extract that data from the request, we use the body-parse
middleware functions. They convert the data into a JavaScript object and add it to the req.body
so that we can get the values.
In this article, we have discussed parsing and getting data from the POST request body using the req.body
object in Express and Node.js server.