11

So I have the following code in my server.js file that I'm running with node.js. I'm using express to handle HTTP requests.

app.post('/api/destinations', function (req, res) {
  var new_destination = req.body;
  console.log(req.body);
  console.log(req.headers);
  db.Destination.create(new_destination, function(err, destination){
    if (err){
      res.send("Error: "+err);
    }
    res.json(destination);
  });
});

I'm running the following in Terminal:

curl -XPOST -H "Content-Type: application/json" -d '{"location": "New York","haveBeen": true,"rating": 4}' http://localhost:3000/api/destinations

After running that server.js prints out the following.

{}
{ host: 'localhost:3000',
  'user-agent': 'curl/7.43.0',
  accept: '*/*',
  'content-type': 'application/json',
  'content-length': '53' }

So req.body is {}. I read other Stack Overflow posts about similar issues where content-type was not correct because of body-parser. But that isn't the issue because content-type is application/json.

Any ideas how to get the actual body of the request?

Thanks in advance.

robertklep
  • 198,204
  • 35
  • 394
  • 381
Charlie Fish
  • 18,491
  • 19
  • 86
  • 179

4 Answers4

31

You need bodyParser.json as well:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
7zark7
  • 10,015
  • 5
  • 39
  • 54
  • This worked. Thanks so much!! Can't believe I forgot that. – Charlie Fish Jul 10 '16 at 18:01
  • 2
    Thank you! Not sure why but when I tried `app.use(bodyParser.json()); ` after reading your comment, it worked, even though I tried it many times before. Must be a magic answer ;) – TetraDev Oct 13 '16 at 20:55
  • 16
    I am still having an empty body despite both lines being included. Not sure why. – Micrified Mar 21 '17 at 22:14
  • 2
    I have done everything you guys advice here, but nothing works. I wonder why this error happen? please good answers! – Miguel Peguero Oct 11 '17 at 22:02
  • Works fine for me: https://gist.github.com/anonymous/72e0e5af4ad10152e90cfccdcb62b836 – 7zark7 Oct 15 '17 at 05:50
  • 4
    You're telling me a f(*@@( web framework won't allow me to access data passed in via a POST unless I extend it?! – Martin Konecny Feb 15 '18 at 01:52
  • Make sure to `JSON.stringify()` the data – Zach Saucier Jul 25 '18 at 17:23
  • I'm actually curious why this isn't the default too? – Jeff Feb 28 '19 at 21:40
  • Newer versions of express require an updated approach: `app.use(express.json());` `app.use(express.urlencoded({ extended: true }));` Also, some answers suggest not using serialize on the browser/client side. Using jQuery, serialize was the only way I got it to work. Stringified payload does not get parsed as expected on the server side. – rhaben Jun 17 '20 at 02:07
16

Sometimes the req.body shows {} if you forgot to put the name attribute to the form input fields. Following is an example:

<input type="email" name="myemail" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>

Then the req.body shows { myemail: 'mathewjohnxxxx@gmail.com' }

I post this answer because, i have encountered the similar problem and this worked for me.

Mathew John
  • 559
  • 6
  • 18
  • 1
    i was wondering why the body parser only works with "name" attributes in inputs, not just "id". This answer helps me a lot, sometimes we just forgot these basic things. Ps: In .NET, I never used names in input fields, so this was unusual to me. – Jone Polvora Nov 21 '17 at 01:50
0

Make sure if you are making the form and inputs in javascript that you append the input to the form. That was my issue.

yourForm.appendChild(yourInput);
Bradyo
  • 63
  • 7
0

For me the back end was configured properly the issue was valid JSON format including double quotes on the variables.

this did not work

      const res = await axios.post(serverPath + "/user/login", {
         email: email,
         password: password,
      });

This DID work (with double quotes around email and password

      const res = await axios.post(serverPath + "/user/login", {
         "email": email,
         "password": password,
      });
Michael Nelles
  • 5,426
  • 8
  • 41
  • 57
  • For JavaScript, `{"email": email, "password": password}` is identical to `{email: email, password: password}` – Charlie Fish Nov 30 '20 at 16:11
  • I agree with you but for what ever reason when axios was parsing this the result was one worked and one did not. I don't have an explanation - just posting in the even that it may save someone time. – Michael Nelles Nov 30 '20 at 18:47