What does the bodyParser() in connect middleware do?
Asked Answered
M

1

20

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);
Mcalpin answered 11/8, 2013 at 12:8 Comment(0)
K
15

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.

Krohn answered 11/8, 2013 at 12:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.