‘req.body’ is used to get the request payload.
Let’s see it with an example.
index.js
const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => res.send("Hello World")) app.post('/users', (req,res) => { console.log(`Received : ${req.body}`) res.status(201).send(`Received : ${req.body}`) }) app.listen(port, () => console.log(`Application started listening on port ${port}!`));
Run index.js
Open postman and fire below post request.
Method: POST
Body:
{
"name"
: "Krishna",
"id" :
"I12345"
}
Set the content-type header to application/json.
When I send the POST request, I got response as
undefined.
Why req.body is
undefined?
By default, req.body is undefined, and is populated when
you use body-parsing middleware such as body-parser and multer.
How to use the
body-parser?
Import body-parser api.
const bodyParser = require('body-parser');
Register the body-parser middlewares with express
application.
// for parsing application/json
app.use(bodyParser.json());
// for parsing application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
index.js
const express = require('express') const bodyParser = require('body-parser'); const app = express() // for parsing application/json app.use(bodyParser.json()); // for parsing application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); app.get('/', (req, res) => res.send("Hello World")) app.post('/users', (req,res) => { var receivedData = JSON.stringify(req.body, null, 0) console.log(`Received: ${receivedData}`) res.send(receivedData) }) const port = 3000 app.listen(port, () => console.log(`Application started listening on port ${port}!`));
Run index.js
Hit the same POST request again.
You can see below message in console and postman.
Received: {"{\r\n
\"name\" : \"Krishna\",\r\n \"id\" :
\"I12345\"\r\n}\r\n\r\n":""}
No comments:
Post a Comment