Express
Express
JS
Express is a lightweight module that wraps the functionality of the
Node.js http module in a simple to use interface.
Express also extends the functionality of the http module to make it
easy for you to handle server routes, responses, cookies, and
statuses of HTTP requests.
To implement Express as the webserver for your Node.js
applications. You learn how to configure the Express server, design
routes, and use the Request and Response objects to send and
receive HTTP requests.
Additionally, you'll learn how to implement template engines.
Getting Started with Express
Configuring Routes
Before the server can accept requests, it's essential to define
routes. A route specifies how to manage the path portion of the URI
in an HTTP request sent to the Express server.
Implementing Routes
There are two parts when defining the route.
First is the HTTP request method (typically GET or POST). Each of these
methods often needs to be handled completely differently.
Second, is the path specified in the URL—for example, / for the root of the
website, /login for the login page, and /cart to display a shopping cart.
The express module provides a series of functions that allow you to
implement routes for the Express server.
These functions all use the following syntax:
app.<method>(path, [callback . . .], callback)
The <method> portion of the syntax actually refers to the HTTP request
method, such as GET or POST.
For example:
app.get(path, [middleware, ...], callback)
app.post(path, [middleware, ...], callback)
The path refers to the path portion of the URL that you want to be handled
by the callback function.
The middleware parameters are 0 or more middleware functions that are
applied before executing the callback function.
The callback function is the request handler that handles the request and
sends the response back to the client.
The callback function accepts a Request object as the first parameter and
a Response object as the second.
For example, the following code implements some basic GET and POST
routes:
app.get('/', function(req, res){
res.send("Server Root");
});
app.get('/login', function(req, res){
res.send("Login Page");
});
app.post('/save', function(req, res){
res.send("Save Page");
});
When the Express server receives an HTTP request, it looks for a route
that has been defined
for the appropriate HTTP method and path. If one is found, a Request and
Response object is created to manage the request and is passed into the
callback function(s) for the route.
Express also provides the app.all() method that works exactly the same as
the app.post() and app.get() methods. The only difference is that the
callback function for app.all() is called on every request for the specified
path regardless of HTTP method. Also, the app.all() method can accept the
* character as a wildcard in the path.
This is a great feature for implementing request logging or other special
functionality to handle requests.
For example:
app.all('*', function(req, res){
// global handler for all paths
});
app.all('/user/*', function(req, res){
// global handler for /user path
});
Applying Parameters in Routes
As you begin implementing routes, you will quickly see that for complex
systems the number of routes can get out of hand. To reduce the number
of routes, you can implement parameters within the URL. Parameters
allow you to use the same route for similar requests by providing unique
values for different requests that define how your application handles the
request and builds the response.
For example, you would never have a separate route for every user or
product in your system.
Instead you would pass in a user ID or product ID as a parameter to one
route, and the server code would use that ID to determine which user or
product to use. There are four main methods for implementing
parameters in a route:
■ Query string: Uses the standard ?key=value&key=value... HTTP query
string after the path in the URL. This is the most common method for
implementing parameters, but the URLs can become long and convoluted.
■ POST params: When implementing a web form or other POST request,
you can pass parameters in the body of the request.
■ regex: Defines a regular expression as the path portion of the route.
Express uses the regex to parse the path of the URL and store matching
expressions as an array of parameters.
■ Defined parameter: Defines a parameter by name using
:<param_name> in the path portion of the route. Express automatically
assigns that parameter a name when parsing the path.
The following sections discuss these methods with the exception of POST
params, which is covered in the next chapter.
Applying Route Parameters Using Query Strings
The simplest method to add parameters to a route is to pass them using
the normal HTTP
query string format of ?key=value&key=value... Then you can use the
url.parse()
method discussed earlier in the book to parse the url attribute of the
Request object to get the
parameters.
The following code implements a basic GET route to /find?
author=<author>&title=<title>
that accepts author and title parameters. To actually get the value of
author and title, the
url.parse() method is used to build a query object:
app.get('/find', function(req, res){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
res.send('Finding Book: Author: ' + query.author +
' Title: ' + query.title);
});
For example, consider the following URL:
/find?author=Brad&title=Node
The res.send() method returns:
Finding Book: Author: Brad Title: Node
Applying Route Parameters Using Regex
One way to implement parameters in routes is to use a regex expression
to match patterns. This
allows you to implement patterns that do not follow a standard /
formatting for the path.
The following code implements a regex parser to generate route
parameters for GET requests
at the URL /book/<chapter>:<page> path. Notice that the values of the
parameters are not
named; instead, req.params is an array of matching items in the URL
path.
app.get(/^\/book\/(\w+)\:(\w+)?$/, function(req, res){
res.send('Get Book: Chapter: ' + req.params[0] +
' Page: ' + req.params[1]);
});
For example, consider the following URL:
/book/12:15
The res.send() method returns
Get Book: Chapter: 12 Page: 15
Applying Route Parameters Using Defined Parameters
If your data is more structured, a defined parameter is a better method to
use than regex. Using
a defined parameter allows you to define your parameters by name within
the route path. You
define parameters in the path of the route using :<param_name>. When
using defined parameters,
req.param is a function instead of an array, where calling
req.param(param_name)
returns the value of the parameter.
The following code implements a basic :userid parameter expecting a URL
with a
/user/<user_id> format:
app.get('/user/:userid', function (req, res) {
res.send("Get User: " + req.param("userid"));
});
For example, consider the following URL:
/user/4983
The res.send() method returns
Get User: 4983