Charlie Fish
Charlie Fish

Reputation: 20566

Express.js POST req.body empty

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.

Upvotes: 11

Views: 27431

Answers (4)

Michael Nelles
Michael Nelles

Reputation: 6032

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,
      });

Upvotes: 0

Bradyo
Bradyo

Reputation: 63

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);

Upvotes: 0

Mathew John
Mathew John

Reputation: 579

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.

Upvotes: 16

7zark7
7zark7

Reputation: 10145

You need bodyParser.json as well:

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

Upvotes: 31

Related Questions