Using Request Objects

You pass a Request object to a route handler as the first parameter. The Request object provides data and metadata about the request, including the URL, headers, query string, and much more. It allows you to handle a request appropriately in your code.

Table 18.2 lists some of the most commonly used properties and methods available for the Request object.

Image

Table 18.2 Properties and methods of the HTTP Request object

Listing 18.3 shows how to access the various parts of the Request object. The output in Figure 18.2 shows the actual values associated with a GET request.

Listing 18.3 express_request.js: Accessing properties of the Request object in Express


01 var express = require('express'),
02 var app = express();
03 app.listen(80);
04 app.get('/user/:userid', function (req, res) {
05   console.log("URL:    " + req.originalUrl);
06   console.log("Protocol:  " + req.protocol);
07   console.log("IP:    " + req.ip);
08   console.log("Path:    " + req.path);
09   console.log("Host:    " + req.host);
10   console.log("Method:    " + req.method);
11   console.log("Query:    " + JSON.stringify(req.query));
12   console.log("Fresh:    " + req.fresh);
13   console.log("Stale:    " + req.stale);
14   console.log("Secure:    " + req.secure);
15   console.log("UTF8:    " + req.acceptsCharset('utf8'));
16   console.log("Connection: " + req.get('connection'));
17   console.log("Headers: " + JSON.stringify(req.headers,null,2));
18   res.send("User Request");
19 });


Image

Figure 18.2 Accessing properties of the Request object.

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

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