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

5

27

This is the code of my server :

var express = require('express');
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());

app.post("/", function(req, res) {
    res.send(req.body);
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

From Postman, I launch a POST request to http://localhost:3000/ and in Body/form-data I have a key "foo" and value "bar".

However I keep getting an empty object in the response. The req.body property is always empty.

Did I miss something?enter image description here

Cardew answered 31/1, 2017 at 10:25 Comment(1)
S
48

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

Stentorian answered 31/1, 2017 at 10:27 Comment(4)
it works if I use x-www-form-urlencoded instead of form-data. But it doesn't work if I set a header "Content-Type" with value "application/json" and use form-data. Any idea why?Cardew
If you set content-type to application/json you can use raw. Just make sure you wrap your keys in ". I'll update answerStentorian
for more details have a look at #5710858Stentorian
Thank you. Could you explain 1- why it can't work with form-data? 2- What is the difference between using x-www-form-urlencoded and raw ; in blog articles I don't see the use of bodyParser.urlencoded() so I guess most don't go for x-www-form-urlencoded whatever that is?Cardew
S
5
let express = require('express');
let app = express();

// For POST-Support
let 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

Subreption answered 28/11, 2018 at 7:49 Comment(2)
This reads more like a game of spot-the-difference than an answer. What did you change? Why should it solve the problem? Does this add anything that R. Gulbrandsen hasn't already said in their accepted answer from last year?Kingwood
This is actually a real time example. It will obviously help.Subreption
R
2

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 post
router.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.

Rashida answered 4/7, 2019 at 6:51 Comment(3)
is this different from other answers? you could have voted those up in case of similar answerGlucoprotein
It would be useful if you can explain how did you use the body-parser! Also, it would be cool if you can give some context regarding what the body-parser is.Pretorius
Nic Sxerman, I have edited and posted the router code in my edit.Rashida
B
0

On more point I want to add is if you created your project through Express.js generator in your app.js it also generates bellow code

app.use(express.json());

if you put your body-parser above this code the req.body will return null or undefined you should put it bellow the above code see bellow for correct placement

 app.use(express.json());
 app.use(bodyParser.urlencoded({extended:true}));
 app.use(bodyParser.json());
Blub answered 9/9, 2019 at 15:58 Comment(1)
This are same. Express has build in body parser app.use(express.json()); will call build in body parser. So you dont need to install body parser after express version 4.16.0Semela
H
0

I experienced the same issue. I tried all that had been suggested here. I decided to console log the value of the request object. It's a huge object. Inside this object I saw this query object carrying my post data:

query: {
    title: 'API',
    content: 'API stands for Application Programming Interface.'
  }

So it turns out that request.query, and not request.body, contains the values I send along with my post request from Postman.

Hiddenite answered 18/9, 2022 at 15:4 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Trautman

© 2022 - 2024 — McMap. All rights reserved.