Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the bodyParser() in connect middleware do?

Tags:

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);
like image 785
Rich Avatar asked Aug 11 '13 12:08

Rich


People also ask

What is bodyParser middleware?

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.

Why is bodyParser needed?

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.

What is app use bodyParser JSON ())?

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.

How use bodyParser express JS?

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.


1 Answers

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.

like image 115
Nitzan Shaked Avatar answered Sep 18 '22 17:09

Nitzan Shaked