MrMangado
MrMangado

Reputation: 993

Receiving req.body empty with post form with Express node.js

I've got a simply form, that sends POST data to my Node.JS server, with Express. This is the form:

<form method="post" action="/sendmessage">
  <div class="ui-widget">
      <input type="text" id="search" data-provide="typeahead" placeholder="Search..." />
  </div>
  <textarea id="message"></textarea>
</form>

The ui-widget and the input is releated with typehead, an autocomplete library from Twitter. And this is how I handle the POST request in the server:

app.post('/sendmessage', function (req, res){

  console.log(req.body);

  usermodel.findOne({ user: req.session.user }, function (err, auser){

        if (err) throw err;

        usermodel.findOne({ user: req.body.search }, function (err, user){

            if (err) throw err;

             var message = new messagemodel({

                  fromuser: auser._id,
                  touser: user._id,
                  message: req.body.message,
                  status: false

             });

             message.save(function (err){

                  if (err) throw err;

                  res.redirect('/messages')

             })

        });

   });

});

The console shows me '{}', and then an error with req.body.search, because search is not defined. I don't know what is happening here, and it's not a problem related with the typehead input. Any solution for this problem...?

Thank's advance!

Upvotes: 6

Views: 21945

Answers (5)

abinner
abinner

Reputation: 1

In my case I did not provide name tags like this name="firstname" in my input field. After adding them, everything worked.

Upvotes: 0

Jorge Avila
Jorge Avila

Reputation: 71

on express 4 would be this one. (note that this will not parse multipart/uploads).

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

and if you want to receive json input

app.use(bodyParser.json());

Upvotes: 6

webjay
webjay

Reputation: 5488

In my case it was caused by my app redirecting http to https. Updating Facebook to use the https uri fixed it.

Upvotes: 0

wesbos
wesbos

Reputation: 26317

I had this problem and it turned out I was using app.use(express.bodyParser()); but it was after the code I was using. Moving it up solved the issue.

Upvotes: 11

Ari Porad
Ari Porad

Reputation: 2922

req.body is made up of names and values.

add name="search" on your search box and try again.

You also must use the express/connect.bodyParser() middleware, thanks Nick Mitchinson!

Upvotes: 22

Related Questions