Can't get POST data using NodeJS/ExpressJS and Postman Can't get POST data using NodeJS/ExpressJS and Postman node.js node.js

Can't get POST data using NodeJS/ExpressJS and Postman


Add the encoding of the request. Here is an example

..app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));..

Then select x-www-form-urlencoded in Postman or set Content-Type to application/json and select raw

Edit for use of raw

Raw

{  "foo": "bar"}

Headers

Content-Type: application/json

EDIT #2 Answering questions from chat:

  1. why it can't work with form-data?

You sure can, just look at this answer How to handle FormData from express 4

  1. What is the difference between using x-www-form-urlencoded and raw

differences in application/json and application/x-www-form-urlencoded


let express = require('express');let app = express();// For POST-Supportlet bodyParser = require('body-parser');let multer = require('multer');let upload = multer();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));app.post('/api/sayHello', upload.array(), (request, response) => {    let a = request.body.a;    let b = request.body.b;    let c = parseInt(a) + parseInt(b);    response.send('Result : '+c);    console.log('Result : '+c);});app.listen(3000);

Sample JSON and result of the JSON:

Sample Json and result of the json

Set Content-typeL application/JSON:

Set Content-type: application/json


I encountered this problem while using routers. Only GET was working, POST, PATCH and delete was reflecting "undefined" for req.body. After using the body-parser in the router files, I was able to get all the HTTP methods working...

Here is how I did it:

...const bodyParser = require('body-parser')...router.use(bodyParser.json());router.use(bodyParser.urlencoded({ extended: true }));......// for postrouter.post('/users', async (req, res) => {    const user = await new User(req.body) // here is where I was getting req.body as undefined before using body-parser    user.save().then(() => {        res.status(201).send(user)    }).catch((error) => {        res.status(400).send(error)    })})

For PATCH and DELETE as well, this trick suggested by user568109 worked.