Handling POST Body Data

Another very common use for Express middleware is to handle body data inside a POST request. The data inside a request body can be in various formats, such as POST parameter strings, JSON strings, or raw data. Express’s body-parser middleware attempts to parse the data in the JSON data in the body of requests and properly format them as the req.body property of the Request object.

For example, if this middleware receives POST parameters or JSON data, it converts them to a JavaScript object and stores it as the req.body property of the Request object. Listing 19.4 illustrates using the body-parser middleware to support reading form data posted to the server.

The code in lines 5–11 handles the GET request and responds with a very basic form. It is not well-formatted HTML, but it is adequate to illustrate the use of the body-parser middleware.

The code in lines 12–21 implements a POST request handler. Notice that in line 16, the first name entered in the form field is accessed using req.body.first to help build the hello message in the response. This really is it. You can handle any kind of form data in the body in this manner. Figure 19.2 shows the resulting web forms in the browser.

Listing 19.4 express_post.js: Handling POST parameters in a request body by using the body-parser middleware


01 var express = require('express'),
02 var bodyParser = require('body-parser'),
03 var app = express();
04 app.use(bodyParser());
05 app.get('/', function (req, res) {
06   var response = '<form method="POST">' +
07         'First: <input type="text" name="first"><br>' +
08         'Last: <input type="text" name="last"><br>' +
09         '<input type="submit" value="Submit"></form>';
10   res.send(response);
11 });
12 app.post('/',function(req, res){
13   var response = '<form method="POST">' +
14         'First: <input type="text" name="first"><br>' +
15         'Last: <input type="text" name="last"><br>' +
16         '<input type="submit" value="Submit"></form>' +
17         '<h1>Hello ' + req.body.first + '</h1>';
18   res.type('html'),
19   res.end(response);
20   console.log(req.body);
21 });
22 app.listen(80);


Image

Figure 19.2 Handling POST parameters in a request body by using the body-parser middleware.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.35.54