npm body parser - estermer/ericstermer.com GitHub Wiki
is a middleware to translate the request.body of server POST route to turn into an Object. It does this by looking at a request, checking if it has a 'body', and turns the body into an object and adds it to a key called 'body' that can be accessed by don notation on the request object.
for example:
//Without Body Parser
app.post('/', function(request, response){
console.log(req.body); //will output undefined
});
//With Body Parser
app.post('/', function(request, response){
console.log(req.body); //will output {key: value}
});
This will allow us to access the information coming from form with DOT notation req.body.key
So if a form set up like this:
<form method="POST" action="/">
<div>
<label for="description">Description:</label>
<input name="description">
</div>
<div>
<label for="description">Description:</label>
<span>yes</span><input type="radio" name="urgent" value="true" checked>
<span>no</span><input type="radio" name="urgent" value="false">
</div>
<div>
<input type="submit" value="Add ToDo">
</div>
</form>
Then we can access the data in a POST in the server like so:
app.post('/', function (req,res) {
console.log(req.body.description);//outputs text from the description input
console.log(req.body.urgent);// outputs true or false
//the keys are the 'name' in the input form
res.redirect('/');
});
run npm install --save body-parser
require it in the top of you server.js var bodyParser = require('body-parser');
then declare use at the top as well app.use(bodyParser.urlencoded({extended: true}));