23

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

user2923322
  • 942
  • 1
  • 6
  • 20

4 Answers4

43

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

Community
  • 1
  • 1
R. Gulbrandsen
  • 3,220
  • 1
  • 20
  • 34
  • 1
    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? – user2923322 Jan 31 '17 at 10:31
  • 1
    If you set `content-type` to `application/json` you can use `raw`. Just make sure you wrap your keys in ". I'll update answer – R. Gulbrandsen Jan 31 '17 at 10:32
  • for more details have a look at http://stackoverflow.com/questions/5710358/how-to-retrieve-post-query-parameters – R. Gulbrandsen Jan 31 '17 at 10:35
  • 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? – user2923322 Jan 31 '17 at 10:38
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

kit
  • 1,150
  • 5
  • 15
  • 22
Goutam Ghosh
  • 87
  • 1
  • 6
  • 1
    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? – Quentin Nov 28 '18 at 08:09
  • This is actually a real time example. It will obviously help. – Goutam Ghosh Nov 28 '18 at 16:23
1

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.

Balepur
  • 103
  • 1
  • 5
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());
MJ X
  • 7,476
  • 10
  • 61
  • 88
  • 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.0 – Hyzyr Feb 09 '22 at 15:01