Getting req.body empty with a mail form using Express node.js

I have a simple form that sends POST data to my Node.JS server using 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> 

ui-widget and login come out using typehead , an autocomplete library from Twitter. And this is how I handle the POST request on 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 undefined. I don't know what is going on here, and this is not a problem with typehead input. Any solution to this problem ...?

Thanks in advance!

+4
source share
4 answers

req.body consists of names and values.

add name="search" in the search field and try again.

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

+18
source

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

+10
source

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

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

and if you want to get json input

 app.use(bodyParser.json()); 
+6
source

In my case, it was caused by redirecting my http application to https . Facebook update for using https uri fixed.

0
source

All Articles