Express.js POST req.body empty
Asked Answered
R

4

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.

Raze answered 10/7, 2016 at 17:41 Comment(5)
You do use the body-parser middleware, right?Teeming
And if you are: how, exactly?Disparate
I am using body-parser. Basically just requiring it then "app.use(bodyParser.urlencoded({ extended: true }));" without the quotes of course.Raze
urlencoded() does not handle application/json (hint).Disparate
Thank you so much @Disparate adding bodyParser.json() fixed it. Can't believe I forgot that.... thanks so muchRaze
C
31

You need bodyParser.json as well:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Clan answered 10/7, 2016 at 18:0 Comment(9)
This worked. Thanks so much!! Can't believe I forgot that.Raze
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 ;)Simulacrum
I am still having an empty body despite both lines being included. Not sure why.Hyden
I have done everything you guys advice here, but nothing works. I wonder why this error happen? please good answers!Feeze
Works fine for me: gist.github.com/anonymous/72e0e5af4ad10152e90cfccdcb62b836Clan
You're telling me a f(*&#@@( web framework won't allow me to access data passed in via a POST unless I extend it?!Sliver
Make sure to JSON.stringify() the dataSatellite
I'm actually curious why this isn't the default too?Kaiak
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.Donnelldonnelly
P
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: '[email protected]' }

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

Polygamous answered 18/10, 2017 at 20:13 Comment(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.Victorious
G
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);
Gripsack answered 19/11, 2019 at 3:59 Comment(0)
S
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,
      });
Sayer answered 30/11, 2020 at 5:27 Comment(2)
For JavaScript, {"email": email, "password": password} is identical to {email: email, password: password}Raze
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.Sayer

© 2022 - 2024 — McMap. All rights reserved.