I'm doing a tutorials on node.js, and the lesson is teaching me how to create a server using node. In the code below, what does the connect.bodyParser() line do?
var app = connect()
.use(connect.bodyParser())
.use(connect.static('public'))
.use(function (req, res) {
if (req.url === '/process') {
res.end(req.body.name + ' would repeat ' + req.body.repeat + ' times.');
} else {
res.end("Invalid Request");
}
})
.listen(3000);
Body-parser is the Node. js body parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it. Installation of body-parser module: You can visit the link to Install body-parser module.
In order to get access to the post data we have to use body-parser . Basically what the body-parser is which allows express to read the body and then parse that into a Json object that we can understand.
use(bodyParser. json()) is to be used independently, whether you set extended as true or false . app. use(bodyParser. json()) basically tells the system that you want json to be used.
To use the Text body parser, we have to write app. use(bodyParser. text()) and the Content-Type in your fetch API would be text/html . That's it, now your backend service will accept POST request with text in the request body.
It populates req.body
with (among other things) the value of the POST
parameters. Here's the doc and examples: http://expressjs.com/api.html#req.body
bodyParser is a part of "Connect", a set of middlewares for node.js. Here's the real docs and source from Connect: http://www.senchalabs.org/connect/bodyParser.html
As you can see, it's simply a thin wrapper that tries to decode JSON, if fails try to decide URLEncoded, and if fails try to decode Multi-Part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With