419

All of a sudden this has been happening to all my projects.

Whenever I make a post in nodejs using express and body-parser req.body is an empty object.

var express    = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded())

// parse application/json
app.use(bodyParser.json())

app.listen(2000);

app.post("/", function (req, res) {
  console.log(req.body) // populated!
  res.send(200, req.body);
});

Via ajax and postman it's always empty.

However via curl

$ curl -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:2000/

it works as intended.

I tried manually setting Content-type : application/json in the former but I then always get 400 bad request

This has been driving me crazy.

I thought it was that something updated in body-parser but I downgraded and it didn't help.

Any help appreciated, thanks.

Phil
  • 157,677
  • 23
  • 242
  • 245
Joseph Dailey
  • 4,735
  • 2
  • 15
  • 18
  • 36
    So you tried explicitly setting the `Content-Type` in postman? If not, you might try that, as I've had issues before with postman not sending a `Content-Type`. – mscdex Jul 03 '14 at 02:28
  • yes I did. that is when I recieved 400: invalid json – Joseph Dailey Jul 03 '14 at 13:30
  • @mscdex - thanks i did not set content-tupe in postman and was getting crazy :) – Muzafar Ali Aug 29 '16 at 16:03
  • For those people who are coming here because they wish to send/upload **files** from their APIs and thus have to use form-data. You need something to handle the form data: https://www.npmjs.com/package/multer is pretty popular package. – Bhaskar Jan 25 '19 at 15:49
  • No matter what, postman doesn't deal with integers and float values very well. If you have integer or float values, ensure to double quote everything, both keys and values – anabeto93 Aug 03 '19 at 15:34
  • Once change your content type to sth else and then again change it to json. this solved my problem – Abadis Mar 10 '20 at 07:57
  • 4
    The real answer if you've done everything right - https://stackoverflow.com/a/61802608/4010017 – kaushalpranav Jul 15 '20 at 16:57
  • 2
    what @kaushalpranav linked to fixed it for me! – friartuck Jan 21 '21 at 05:29
  • If anyone here is trying to set a content security policy (csp) reporting uri, the content type is often not application/javascript. See this answer for options: https://stackoverflow.com/questions/64436936/content-security-policy-report-empty-object-in-express – MaxPRafferty May 20 '21 at 20:57

31 Answers31

399

In Postman of the 3 options available for content type select "X-www-form-urlencoded" and it should work.

Also to get rid of error message replace:

app.use(bodyParser.urlencoded())

With:

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

See https://github.com/expressjs/body-parser

The 'body-parser' middleware only handles JSON and urlencoded data, not multipart

As @SujeetAgrahari mentioned, body-parser is now inbuilt with express.js.

Use app.use(express.json()); to implement it in recent versions for JSON bodies. For URL encoded bodies (the kind produced by HTTP form POSTs) use app.use(express.urlencoded());

O. Jones
  • 103,626
  • 17
  • 118
  • 172
Mick Cullen
  • 9,214
  • 3
  • 21
  • 17
  • That worked for postman, I'm not sure why it works with ajax as I didn't change anything. – Joseph Dailey Jul 03 '14 at 21:53
  • For some reason http posts via Angular did not need to be URL encoded, but ajax calls did. Anyone know why? – youngrrrr Mar 31 '16 at 12:38
  • This worked for me, why wasn't it working with raw encoded though? – Daniel Kobe Aug 01 '16 at 01:35
  • 52
    now body-parser is inbuilt with express.js just use `app.use(express.json());` – sujeet Sep 27 '19 at 10:28
  • 1
    I had the same problem. I made sure that I configured express correctly and the problem still occurred. The mistake was that I set the `Content-Type` in postman before making any requests and the problem was solved when I restarted postman. – Youssef AbouEgla May 15 '20 at 21:38
  • 2
    for some reason, a request from another service to my app (a webhook) is parsed correctly when I use `app.use(express.urlencoded());`, but not with `app.use(express.json());` (`request.body` is `{}`, an empty object). If anybody has an idea why, please share. – YakovL Feb 04 '21 at 09:16
  • @SujeetAgrahari Make it an answer please. I also don't understand how express doesn't handle such basic by itself. – Ambroise Rabier Aug 20 '21 at 11:42
  • It is worth noting that ```app.use(express.json());``` needs to be placed before ```app.get```/```app.post``` to work. – Ovidijus Parsiunas Mar 04 '23 at 01:43
306

With Postman, to test HTTP post actions with a raw JSON data payload, select the raw option and set the following header parameters:

Content-Type: application/json

Also, be sure to wrap any strings used as keys/values in your JSON payload in double quotes.

The body-parser package will parse multi-line raw JSON payloads just fine.

{
    "foo": "bar"
}

Tested in Chrome v37 and v41 with the Postman v0.8.4.13 extension (body-parser v1.12.2 and express v4.12.3) with the setup below:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

// ... Your routes and methods here

Postman raw json payload

MLM
  • 3,660
  • 3
  • 41
  • 66
sirthud
  • 3,061
  • 1
  • 13
  • 2
  • Wrapping any strings used as key/values in double quotes... Easy to miss but a total deal breaker otherwise! Thank you. – jagershark Jul 28 '17 at 23:45
  • 3
    When use `form-data` in Postman to post the data, I always get the `{}` in the req.body. Should I set the `Content-Type` option? – mingchau Apr 07 '19 at 14:06
97

I discovered, that it works when sending with content type

"application/json"

in combination with server-side
app.use(express.json())
(As @marcelocra pointed out, the 2022 version would use)

(old version for reference)
app.use(bodyParser.json());

Now I can send via

var data = {name:"John"}
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", theUrl, false); // false for synchronous request
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(data);

and the result is available in request.body.name on the server.

Xan-Kun Clark-Davis
  • 2,664
  • 2
  • 27
  • 38
78

I made a really dumb mistake and forgot to define name attributes for inputs in my html file.

So instead of

<input type="password" class="form-control" id="password">

I have this.

<input type="password" class="form-control" id="password" name="password">

Now request.body is populated like this: { password: 'hhiiii' }

Jason Kim
  • 18,102
  • 13
  • 66
  • 105
24

You have to check whether the body-parser middleware is set properly to the type of request(json, urlencoded).

If you have set,

app.use(bodyParser.json());

then in postman you have to send the data as raw.

https://i.stack.imgur.com/k9IdQ.png postman screenshot

If you have set,

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

then 'x-www-form-urlencoded' option should be selected.

Tuan
  • 635
  • 1
  • 8
  • 15
  • 1
    what about having both them? (bodyParser.urlencoded and bodyParser.json())... which one can I use in postman? – Tommy Leong Mar 11 '20 at 08:53
22

I ran into this problem today, and what fixed it was to remove the content-type header in Postman! Very strange. Adding it here in case it helps someone.

I was following the BeerLocker tutorial here: http://scottksmith.com/blog/2014/05/29/beer-locker-building-a-restful-api-with-node-passport/

stone
  • 8,422
  • 5
  • 54
  • 66
  • 2
    i had the same issue. having the header "unchecked" (and greyed out) was not enough, i had to completely remove it. even though the ">" source button shows that i was not sending that header with the Content-Type being in the unchecked state, it still needed to be completely removed. – theRemix Aug 25 '15 at 08:29
  • I can't figure out how to remove the default headers in the postman chrome extension... are you using the app maybe? – WestleyArgentum May 02 '16 at 06:09
  • Oh, I installed the app and it works much better than the extension. Sorry for the noise. – WestleyArgentum May 02 '16 at 06:19
20

If you are doing with the postman, Please confirm these stuff when you are requesting API

enter image description here

vignesh
  • 2,356
  • 1
  • 14
  • 21
20

For express 4.16+, no need to install body-parser, use the following:

const express = require('express');
const app = express();
app.use(express.json());

app.post('/your/path', (req, res) => {
    const body = req.body;
    ...
}
Ashwin
  • 7,277
  • 1
  • 48
  • 70
  • 1
    Solved it for me. Using it to get body of PUT request. `body-parser` returned empty json body – A.W. Dec 30 '20 at 15:01
15

My problem was I was creating the route first

// ...
router.get('/post/data', myController.postHandler);
// ...

and registering the middleware after the route

app.use(bodyParser.json());
//etc

due to app structure & copy and pasting the project together from examples.

Once I fixed the order to register middleware before the route, it all worked.

fiat
  • 15,501
  • 9
  • 81
  • 103
14

Express 4.17.1

Server middleware example like this without bodyParser;

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

If you're GET requesting header should be like this;

{'Content-Type': 'application/json'}

If you're POST requesting header should be like this;

{'Content-Type': 'application/x-www-form-urlencoded'}

I'am using on client side simple functions like this;

async function _GET(api) {
    return await (await fetch(api, {
        method: 'GET',
        mode: 'no-cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Connection': 'keep-alive',
            'Accept': '*',
        },
    })).json();
};

async function _POST (api, payload) {
    return await (await fetch(api, {
        method: 'POST',
        mode: 'no-cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Connection': 'keep-alive',
            'Accept': '*/*',
        },
        body: new URLSearchParams(payload),
    })).json();
};
Fatih Mert Doğancan
  • 1,016
  • 14
  • 21
10

In postman, even after following the accepted answer, I was getting an empty request body. The issue turned out to be not passing a header called

Content-Length : <calculated when request is sent>

This header was present by default (along with 5 others) which I have disabled. Enable this and you'll receive the request body.

kaushalpranav
  • 1,725
  • 24
  • 39
  • 1
    Also, make sure the tool you are using for sending the requests sends the proper headers in general. In my case, I used a different tool with the exact same request and it worked. – MRadev May 02 '22 at 16:44
9

The error source is not defining the specific header type when the postman request is made. I simply solved it by either adding

Content-Type: application/json

Or explicitly defining the raw data type as JSON in postman while making the request also solves the problem.

hillsonghimire
  • 485
  • 5
  • 13
4

Even when i was learning node.js for the first time where i started learning it over web-app, i was having all these things done in well manner in my form, still i was not able to receive values in post request. After long debugging, i came to know that in the form i have provided enctype="multipart/form-data" due to which i was not able to get values. I simply removed it and it worked for me.

Shaggie
  • 1,799
  • 7
  • 34
  • 63
  • yes, this also worked to get the form body **but** then caused another problem with my form - basically the file could not be uploaded as this requires `enctype="multipart/form-data"` – tsando Apr 11 '18 at 10:29
  • btw, just to add to my above comment, I managed to get this working with `multer` - see documentation on https://www.npmjs.com/package/multer – tsando Apr 11 '18 at 11:16
4

I solved this using multer as suggested above, but they missed giving a full working example, on how to do this. Basically this can happen when you have a form group with enctype="multipart/form-data". Here's the HTML for the form I had:

<form action="/stats" enctype="multipart/form-data" method="post">
  <div class="form-group">
    <input type="file" class="form-control-file" name="uploaded_file">
    <input type="text" class="form-control" placeholder="Number of speakers" name="nspeakers">
    <input type="submit" value="Get me the stats!" class="btn btn-default">            
  </div>
</form>

And here's how to use multer to get the values and names of this form with Express.js and node.js:

var multer  = require('multer')
var upload = multer({ dest: './public/data/uploads/' })
app.post('/stats', upload.single('uploaded_file'), function (req, res) {
   // req.file is the name of your file in the form above, here 'uploaded_file'
   // req.body will hold the text fields, if there were any 
   console.log(req.file, req.body)
});
tsando
  • 4,557
  • 2
  • 33
  • 35
3

Make sure ["key" : "type", "value" : "json"] & ["key":"Content-Type", "value":"application/x-www-form-urlencoded"] is in your postman request headers

vpage
  • 71
  • 2
3

It seems if you do not use any encType (default is application/x-www-form-urlencoded) then you do get text input fields but you wouldn't get file.

If you have a form where you want to post text input and file then use multipart/form-data encoding type and in addition to that use multer middleware. Multer will parse the request object and prepare req.file for you and all other inputs fields will be available through req.body.

Mohammad Haque
  • 565
  • 1
  • 7
  • 16
  • 2
    thanks - `multer` was indeed the solution to my problem. It would be good if you could add an example on how to use this as part of your answer – tsando Apr 11 '18 at 11:17
3

I believe this can solve app.use(express.json());

3

I solved this by changing the enctype of my form on the front-end:

  • It was ⛔️ <form enctype="multipart/form-data">
  • I changed it for ✅ <form enctype="application/json">

It was a relief to see the data eventually pop into the console ^^

Titi
  • 51
  • 4
  • This was my problem, ever since I upgraded mongoose from v6 to v7 and using the latest nodejs. – Kennyb Apr 10 '23 at 13:10
2

A similar problem happened to me, I simply mixed the order of the callback params. Make sure your are setting up the callback functions in the correct order. At least for anyone having the same problem.

router.post('/', function(req, res){});
Henry Ollarves
  • 509
  • 7
  • 18
  • I solved my problems removing any express.json() express.urlencode() or bady-parse and writing so app.post('/path',function(req,res){ data="" // we can access HTTP headers req.on('data', chunk => { data+=chunk }) req.on('end', () => { console.log(data) js=JSON.parse(data) }) }) – Lorenzo Eccher Oct 19 '21 at 23:23
2

I didn't have the name in my Input ... my request was empty... glad that is finished and I can keep coding. Thanks everyone!

Answer I used by Jason Kim:

So instead of

<input type="password" class="form-control" id="password">

I have this

<input type="password" class="form-control" id="password" name="password">
1

you should not do JSON.stringify(data) while sending through AJAX like below.

This is NOT correct code:

function callAjax(url, data) {
    $.ajax({
        url: url,
        type: "POST",
        data: JSON.stringify(data),
        success: function(d) {
            alert("successs "+ JSON.stringify(d));
        }
    });
}   

The correct code is:

function callAjax(url, data) {
    $.ajax({
        url: url,
        type: "POST",
        data: data,
        success: function(d) {
            alert("successs "+ JSON.stringify(d));
        }
    });
}
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
Achilles Ram Nakirekanti
  • 3,623
  • 1
  • 21
  • 13
  • a key thing to note here is that in type, make sure you capitalize "POST". I've seen instances where just using "post" has lead to blank req.body. – Matt C. Nov 27 '19 at 16:52
1

I had the same problem a few minutes ago, I tried everything possible in the above answers but any of them worked.

The only thing I did, was upgrade Node JS version, I didn't know that upgrading could affect in something, but it did.

I have installed Node JS version 10.15.0 (latest version), I returned to 8.11.3 and everything is now working. Maybe body-parser module should take a fix on this.

Phi
  • 504
  • 3
  • 13
  • 30
1

My problem was creating the route first require("./routes/routes")(app); I shifted it to the end of the code before app.listen and it worked!

1

Make sure that you have removed the enctype attribute at the form tag when the form is not containing any file upload input

enctype='multipart/form-data
Sathnindu Kottage
  • 1,083
  • 6
  • 17
1

Check your HTML tag name attribute

<input name="fname">

body-parser use tag name attribute to identify tag's.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
1

I simply solved the issue removing any .json() or .urlencode() for app.use() both for express and body-parser because they gave me some problems. I wrote my code recreating streaming with this simply solution

app.post('/mypath',function(req,res){
   data=""
   // we can access HTTP headers
   req.on('data', chunk => {
      data+=chunk
   })
   req.on('end', () => {
      console.log(data)
      // here do what you want with data
      // Eg: js=JSON.parse(data)
   })
}
Lorenzo Eccher
  • 301
  • 2
  • 4
0

I was using restify instead of express and ran into the same problem. The solution was to do:

server.use(restify.bodyParser());
Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Prabhat
  • 4,066
  • 4
  • 34
  • 41
0

Change app.use(bodyParser.urlencoded()); in your code to

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

and in postman, in header change Content-Type value from application/x-www-form-urlencoded to application/json

Ta:-)

taras
  • 6,566
  • 10
  • 39
  • 50
Abhijith Brumal
  • 1,652
  • 10
  • 14
0

Thank you all for your great answers! Spent quite some time searching for a solution, and on my side I was making an elementary mistake: I was calling bodyParser.json() from within the function :

app.use(['/password'], async (req, res, next) => {
  bodyParser.json()
  /.../
  next()
})

I just needed to do app.use(['/password'], bodyParser.json()) and it worked...

musiquarc
  • 91
  • 2
0

In my case, I was using Fetch API to send the POST request and in the body, I was sending an object instead of a string.

Mistake -> { body: { email: 'value' } }

I corrected by stringifying the body -> { body: JSON.stringify({ email: 'value' }) }

0

Just a quick input - I had the same problem(Testing my private api with insomnia) and when I added the Content-Type: application/json, it instantly worked. What was confusing me was that I had done everything pretty much the same way for the GET and POST requests, but PUT did not seem to work. I really really hope this helps get someone out of the rabbit hole of debugging!

Nikibiki
  • 1
  • 3