0% found this document useful (0 votes)
93 views

Express

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Express

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

IMPLEMENTING EXPRESS IN NODE.

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

 To get started with Express in your Node.js projects, simply install


the express module by running the following command in your
project's root directory:
npm install express
 You can also include Express in your package.json file to ensure it
gets installed when you deploy your application.
 After installing Express, you'll need to create an instance of the
Express class to serve as the HTTP server for your Node.js
application.
 The code snippet below demonstrates how to import the express
module and create an instance that you can utilize:
var express = require('express');
var app = express();
Configuring Express Settings
 Express provides several application settings that control the
behavior of the Express server.
 These settings define the environment as well as how Express
handles JSON parsing, routing, and views.
 Table lists the different settings that can be defined on an express
object.
 The express object provides the set(setting, value) and
enable(setting) and disable(setting) methods to set the value of the
application settings. For example, the following lines of code enable
the trust proxy setting and set the view engine to pug:
app.enable('trust proxy');
app.disable('strict routing');
app.set('view engine', 'pug');
 To get the value of a setting, you can use the get(setting),
enabled(setting), and disabled(setting) methods. For example:
app.enabled('trust proxy'); \\true
app.disabled('strict routing'); \\true
app.get('view engine'); \\pug
Starting the Express Server
 To begin implementing Express as the HTTP server for your Node.js
application, you need to create an instance and begin listening on a
port. The following three lines of code start a rudimentary Express
server listening on port 8080:
var express = require('express');
var app = express();
app.listen(8080);
 The app.listen(port) call binds the underlying HTTP connection to
the port and begins listening on it. The underlying HTTP connection
is the same connection produced using the listen() method on a
Server object created using the http library.
 The value returned by express() is actually a callback function that
maps to the callback function that is passed into the
http.createServer() and https.createServer() methods.

Example: Implementing HTTP and HTTPS Servers


Here’s an example that demonstrates how to set up both HTTP and HTTPS
servers using Express:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
host: '127.0.0.1',
key: fs.readFileSync('ssl/server.key'),
cert: fs.readFileSync('ssl/server.crt')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
app.get('/', function(req, res){
res.send('Hello from 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

You might also like