What is req.body in ExpressJS
In this article, you will learn about what is req.body in ExpressJS and, how to use it.
ExpressJS is a very popular and open-source backend web application framework for NodeJS. In express, you will get req.body property. Basically, it is an object that will allow you to access data from the client-side in the form of a string or JSON Object. It will remain undefined by default and to make things work you need to take some help from middleware like express.json(), express.urlencoded().
In expressJS, to work with req.body object, you need to install express in your local machine first. To install express you need to apply the following command
npm install express
//or
npm i express
Let’s see an example of req.body in the express. In the following example, we will do a post request with the help of the postman and print the data in the console.
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.post('/student-info',(req,res) => {
let data = req.body
console.log('Name : ', data.name)
console.log('Subject : ', data.subject)
res.send()
})
const PORT = 8000
app.listen(PORT,()=>{
console.log(`App is running on Port ${PORT}`)
})
Here, we simply require the express and then store it into the app. After that, we use some middleware that we have mentioned in the earlier section so that our req.body object can work properly. We make a post request and we will catch the data from the client-side and print it in the console, finally, we create our server that is running on port 8000. Let’s see the output below:
Output
In the postman, we have given this information of a student.
{
"name" : "Rohit",
"subject" : "CSE"
}
Let’s check the output in our console. To see the output we need to run our program first and to do so we are giving this command – node app.js, In your case, the file name may be different so you need to type node and your filename and then hit the enter button.
Here, we can print the exact data in our console from the client-side and this is possible because of the req.body and you may get an overview of what is req.body in the ExpressJS from this article.