Rick L. - Express - Js - Guide Book On Web Framework For Node - Js (2016)
Rick L. - Express - Js - Guide Book On Web Framework For Node - Js (2016)
js
Guide Book on Web framework for
Node.js
By Rick L.
Copyright©2016 Rick L.
All Rights Reserved
Copyright © 2016 by Rick L.
All rights reserved. No part of this publication may be reproduced, distributed, or
transmitted in any form or by any means, including photocopying, recording, or other
electronic or mechanical methods, without the prior written permission of the author,
except in the case of brief quotations embodied in critical reviews and certain other
noncommercial uses permitted by copyright law.
Table of Contents
Introduction
Chapter 1- Overview of ExpressJS
Chapter 2- Session
Chapter 3- serve-index
Chapter 4- cookie- Sessions
Chapter 5- Morgan in ExpressJS
Chapter 6- CORS
Chapter 7- Express-Paginate
Chapter 8- Multer
Chapter 9- Compression
Chapter 10- csurf
Chapter 11- body-parser
Chapter 12- Flash
method-override
Chapter 13- serve-favicon
Chapter 14- response-time
Chapter 15- express-namespace
Chapter 16- express-expose
Chapter 17- connect-render
Conclusion
Disclaimer
While all attempts have been made to verify the information provided in this book,
the author does assume any responsibility for errors, omissions, or contrary
interpretations of the subject matter contained within. The information provided in
this book is for educational and entertainment purposes only. The reader is responsible for
his or her own actions and the author does not accept any responsibilities for any liabilities
or damages, real or perceived, resulting from the use of this information.
The trademarks that are used are without any consent, and the publication of the
trademark is without permission or backing by the trademark owner. All
trademarks and brands within this book are for clarifying purposes only and are the
owned by the owners themselves, not affiliated with this document.
Introduction
ExpressJS is one of the most useful and interesting Node frameworks. It is used for the
development of both web and mobile applications. These types of applications are the
mostly widely used in software environments. This shows the need for you to know how
this framework can be used for development. The framework has numerous modules
which can be used for the purpose of enhancing the look and feel of your applications.
Chapter 1- Overview of ExpressJS
ExpressJS is a Node framework which is very flexible and provides developers with
numerous features for the development of web and mobile applications. The framework
can be used for the development of APIs. In this book, we will discuss the various features
of ExpressJS.
Chapter 2- Session
The above command will install the session into your system. To use it in your program,
The session middleware can be created by use of the given “options.” You should know
that the data for the session should not be saved in the cookie itself, but here, only the
session ID is stored. The data for the session is stored on the server side for the app.
However, “MemoryStore,” which is the default server-side session storage was not
developed for use in a production environment. In most cases, it will leak and not scale
“express-session” will accept the following properties in the object for options:
Cookie
These are the settings for the cookie of the session ID. Consider the example given below:
This is a function which is called for generation of a new session ID. The function
provided should return a string which will be used as the session ID. “req” is given to the
function as the first argument in case there is a need for a value to be attached to the “req”
when the ID is being generated. The default value for this will be a function which can use
Note: To avoid confliction of the sessions, make sure that the generated IDs are unique,
that is, they should be different from each other. Consider the example given below which
shows how this can be done:
application.use(session({
genid: function(req) {
},
secret: ‘ my secret ‘
}))
Name
This is the name of the session ID cookie which is to be set in the response. Note that it is
read from the request. The default value for this is the “connect.sid.” For those who have
multiple apps which are running on the same host, then the session cookies have to be
separated from each other. To achieve this, one has to set different names in each of the
apps.
Proxy
Whenever you are setting secure cookies, you have to trust the reverse proxy. This can be
done via the header for “X-Forwarded-Proto.” The default value for this is “undefined.”
2. “false”- all of the headers will be ignored, and the connection will be considered
only if a direct “TLS/SSL” connection exists.
3. “Undefined”- this will use the settings for “trust proxy” from the Express itself.
Resave
This will force the session to be saved back to the session store. This happens whether or
not the session was modified during the request. The necessity of this will depend on your
session store. However, if a client makes parallel requests, race conditions may be created.
Rolling
The cookie will be forced to be set on each of the responses. The expiration date is also
saveUninitialized
With this, a session which was not initialized will be saved to the session store. An
uninitialized session is one which is new and not modified in any way. The default setting
for this is “true.” However, this has deprecated and is expected to change in the future.
Required option
This is the secret which is used for signing the cookie for the session ID. It can be made
up of an array of secrets or a string just for a single secret. In case you provide an array of
secrets, only the first element in the array will be used for signing the cookie for the
session ID. The rest of the elements will be used for verification of the signature in
requests.
Store
This is the instance of the session store. Its default is a new “MemoryStore” instance.
application.use(session({
secret: ‘my secret’,
resave: false,
saveUninitialized: true,
}))
We need to be able to use the cookies in a production environment, and at the same time
allow for testing in a development environment. The setup can be enabled by use of the
“NODE_ENV.” Consider the example given below, which shows how this can be done:
var session = {
secret: ‘ my secret ‘,
cookie: {}
application.use(session(session))
The default setting for “cookie.maxAge” is “null,” and it will never expire, which means
that the cookie will become a browser-session cookie. The cookie is only removed once
the user has closed the browser. The session is also removed.
req.session
For session data to be stored and accessed, you should use the property “req.session,” and
the store initializes this as a JSON. The session objects will then be left fine. Consider the
example given below, which shows a view counter which is specific to a user:
if (session.views) {
session.views++
res.setHeader(‘Content-Type’, ‘text/html’)
res.end()
} else {
session.views = 1
})
Session.regenerate()
This method is invoked when we want to generate the session. After this, a new session
instance and SID will be initialized at the “req.session.” This is shown below:
req.session.regenerate(function(error) {
})
Session.destroy()
With this, the session is destroyed, and the “req.session” removed. It will then be
regenerated in the next request. This is shown below:
req.session.destroy(function(error) {
})
Session.reload()
req.session.reload(function(error) {
})
Session.save()
req.session.save(function(error) {
})
Consider the example given below, which uses the “express-session” so as to store the
application.use(session({
secret: ‘ my secret ‘,
resave: false,
saveUninitialized: true
}))
if (!vws) {
vws = req.session.views = {}
vws[pathname] = (vws[pathname] || 0) + 1
next()
})
})
})
That is how sessions can be used in ExpressJS.
Chapter 3- serve-index
This is used for serving pages having listings of a directory to a particular path. It can be
installed by executing the command given below:
The above command will install the “serve-index” to your computer. To use it in your
program, it has to be included or called by use of the “require” method. This is shown
below:
serveIndex(path, options)
This will return the middleware which serves the index of the directory in the “path” you
have given. The path here is based off of the value for “req.url.” For you to change the
The following properties are accepted by the serve index in the options object:
Filter
This filter function is applied to files. Its default value is “false.” It is called for each of the
files, and it uses the signature “filter(filename, index, files, dir).” “Filename” will be the
file’s name, “index” will be the array index, and “files” is the array of the files, while
Hidden
This is used for displaying the hidden files. Its default value is “false.”
Icons
This is for displaying icons. It default value is “false.”
Stylesheet
This is an optional path which leads to the CSS stylesheet. Its default value is the built-in
stylesheet.
Template
This is an optional path which leads to an HTML template, and is used for rendering the
HTML string.
View
Consider the example given below, which shows how all the above can be used:
// The Serve directory works to indexe for public/ftp folder (having icons)
// Creating a server
})
})
// Listen
server.listen(3000)
application.listen()
Chapter 4- cookie- Sessions
This is a module which is used for providing guest sessions so that each of the visitors will
have a session, whether authenticated or not. In case the session is new, the property “Set-
Cookie” will be produced, regardless of whether you are populating the session.
For the API to be used in the program, we have to use the “require” command as shown
below:
The following options are accepted in the cookie session in the options object:
Name
This is the name of the cookie which is to be set. Its default value is “session”.
Keys
This is the list of the keys to be used for signing and verifying the cookie values. Cookies
which have been set are always signed with the “keys[0].” The rest of the keys will then
be valid for the purpose of verification, and this will allow for the rotation to be done.
Secret
This is a string which will be used as a secret key in case the “keys” are not provided.
There is also a number of cookie options which you need to know how to use.
req.session = null
Consider the simple view counter example given below. Here is the example:
application.use(cookieSession({
name: ‘session’,
}))
req.session.views = (req.session.views || 0) + 1
// Writing the response
res.end(req.session.views + ‘ views’)
})
application.listen(3000)
application.use(cookieSession({
name: ‘session’,
}))
// This will allow you to set req.session.maxAge for letting certain sessions
})
You have to note that the entire session object will be encoded and stored in a cookie. The
maximum cookie size limit on the different browsers can then be exceeded. If the session
object is large enough and it can exceed the limit of the browser when it has been encoded,
what will happen in most cases is that the browser will refuse or avoid storing the cookie.
Chapter 5- Morgan in ExpressJS
This is logger middleware for the HTTP request for Node.js. To use the API in your
program, you have to use the “require” keyword as shown below:
morgan(format, options)
Immediate
The log line should be written on request rather than on response. This will mean that the
requests will always be logged even if the server itself crashes, but it will be impossible
Skip
This is a function used for the determination of whether or not logging was skipped. The
default value for this is “false,” Consider the example given below, which shows how the
morgan(‘combined’, {
})
Stream
This is an output stream which is used for writing log lines, and its default value is
“process.stdout.”
Consider the example given below, which shows how all the requests can be logged in the
application.use(morgan(‘combined’))
res.send(‘hello, there!’)
})
res.setHeader(‘content-type’, ‘text/plain’)
res.end(‘hello, there!’)
})
})
Consider the example given below, which shows how the requests can be logged in
Apache combined format to our file “access.log”:
var fs = require(‘fs’)
res.send(‘hello, there!’)
})
In the example given below, the app will log all the requests in the Apache combined
format to any of the log files in our directory “log/” by use of the file-stream-rotator
var fs = require(‘fs’)
fs.existsSync(lDirectory) || fs.mkdirSync(lDirectory)
frequency: ‘daily’,
verbose: false
})
res.send(‘hello, there!’)
})
In the next app, we will use the custom token formats. It works by adding an ID to all of
the requests, and will then display it by use of the “:id” token. Here is the app:
var id = require(‘node-uuid’)
return req.id
})
application.use(assignid)
res.send(‘hello, world!’)
})
req.id = uuid.v4()
next()
}
Chapter 6- CORS
, cors = require(‘cors’)
, application = express();
application.use(cors());
application.listen(80, function(){
});
, cors = require(‘cors’)
, application = express();
res.json({msg: ‘This has the CORS enabled for all the origins!’});
});
application.listen(80, function(){
console.log(‘ web server which is CORS enabled now listening on port 80’);
});
To configure the CORS, do it as follows:
, cors = require(‘cors’)
, application = express();
var cOptions = {
origin: ‘http://sample.com’
};
application.listen(80, function(){
});
, application = express();
var cOptions = {
callback(null, orIsWhitelisted);
};
});
application.listen(80, function(){
});
How to enable CORS Pre-Flight
Certain requests for CORS are considered to be complex, and these need an initial
OPTIONS request. A CORS request which uses the HTTP verb is considered to be
complex compared to the one which uses POST/GET/HEAD or the one using custom
headers. For pre-fighting to be enabled, a new OPTIONS handler has to be added for the
, cors = require(‘cors’)
, application = express();
});
application.listen(80, function(){
});
, cors = require(‘cors’)
, application = express();
var cOptions;
cOptions = { origin: true }; // reflecting (enabling) the requested origin in our CORS
response
}else{
callback(null, cOptions); // callback needs two parameters: error and the options
};
});
application.listen(80, function(){
console.log(‘ web server with CORS enabled is listening on port 80’);
});
This is to be used together with the pagination plugins for databases such as the
MongoDB.
For it to be used in the program, one has to use the “require” keyword so as to include it
into the program This is shown below:
// # app.js
// keeping this before all the routes that will use pagination
application.use(paginate.middleware(10, 50));
res.format({
html: function() {
res.render(‘users’, {
users: users,
pageCount: pageCount,
itemCount: itemCount
});
},
json: function() {
res.json({
object: ‘list’,
has_more: paginate.hasNextPages(req)(pageCount),
data: users
});
});
});
});
application.listen(3000);
//- users.jade
h1 Users
//- you must have noticed that we only have to pass the querystring param
//- this will assume that you have `?age=1` or `?age=-1` in the querystring
//- so the values will be negated by this and you will be given
//- an opposite sorting order ( that is, desc with -1 or asc with 1)
ul
li= myuser.email
include _paginate
//- _paginate.jade
//- In this example, we will make use of the Bootstrap 3.x pagination classes
if paginate.hasPreviousPages || paginate.hasNextPages(pageCount)
.navigation.well-sm#pagination
ul.pager
if paginate.hasPreviousPages
li.previous
a(href=paginate.href(true)).prev
i.fa.fa-arrow-circle-left
| Previous
if paginate.hasNextPages(pageCount)
li.next
a(href=paginate.href()).next
| Next
i.fa.fa-arrow-circle-right
Chapter 8- Multer
top of “busboy.” You have to note that any form which is not multipart cannot be handled
by Multer.
It works by adding a “body” and a “file/files” object to the “request” object. In the “body”
object, the values for the form fields will be stored. The “file/files” object will contain the
Consider the example given below which shows how this can be done:
})
})
//
// example
//
For those who are in need of handling a text which is in multipart form, any of the Multer
methods can be used. These methods include the “single(),” “.array(),” and “fields().”
Consider the example given below, which shows how the “.array()” can be used:
})
With Multer, an options object is accepted, in which the most basic one is our “dest”
property, and it specifies the destination of our uploaded files. If the options object is
omitted, the files which you upload will be kept in the memory other than in the disk.
To avoid conflicts brought by naming, the Multer will rename the files and this is its
default setting. The rest of the function can be customized according to what you need.
There exists a variety of options which can be passed to the Multer, so make sure that you
In a normal web application, only the “dest” property might be required, and this can be
For those who are in need of exercising a greater control on your uploaded files, just use
the “storage” property other than the “dest” property. “DiskStorage” and
“MemoryStorage” storage engines are shipped with Multer. You can use third parties so as
If you need to exercise full control of your files which are stored on the disk, use the disk
},
})
The only two options which are available include the “filename” and “destination.” They
are the functions which determine how the files are to be stored. The”destination”
property will determine the folder in the directory in which the uploaded file is to be
stored. This can also be specified as a path in the program. If this property is not
File Filter
This property can be used for setting the files which are to be uploaded and the ones which
are to be skipped. This function should be used as shown in the example given below:
cb(null, false)
cb(null, true)
// you can pass an error since something may go wrong at some point:
}
Error Handling
When an error has been encountered, the Multer will pass it to Express. The standard
Express error way can be used for the purpose of displaying an error.
For you to catch the errors which are originating from the Multer, just call the middleware
if (error) {
return
})
})
That is how it can be used.
Chapter 9- Compression
deflate
gzip
To include this API in your program, use the “require” keyword as shown below:
There are different options which can be used so as to return the compression middleware.
.filter
This is the default filter function. It is used for construction of a custom filter function
which will be an extension of our default function. The example given below shows how
application.use(compression({filter: compress}))
if (req.headers[‘x-no-compression’]) {
return false
red.flush()
With this module, the response which has been compressed partially is flushed to the
express/connect
This module can be used by use of the “app.use,” which is available in either Express and
connect. Requests passed through the middleware are always compressed. Consider the
application.use(compression())
The working of this module with server-side is not done out of the box. For content to be
compressed, a window for the output has to be buffered up so that we can get a good
compression.
To do all this, we have to call the “red.flush()” for those who need the data written so as to
application.use(compression())
res.setHeader(‘Content-Type’, ‘text/event-stream’)
res.setHeader(‘Cache-Control’, ‘no-cache’)
res.write(‘data: ping\n\n’)
res.flush()
}, 2000)
res.on(‘close’, function () {
clearInterval(timer)
})
})
Chapter 10- csurf
This is a token middleware for CSRF. It acts as a middleware for protection purposes. For
it to be used, one has to begin by initializing a cookie-parser or a session middleware. It
To use the API in your program, use the “require” command as shown below:
The options for this module take multiple and different objects which you can learn how
to use.
Consider the example given below, which shows a code for the server-side which can be
used for generation of the CSRF form which can be used for posting back. This is the
example:
// parsing cookies
application.use(cParser())
})
})
Inside your view, the value for csrfToken should be set to the value of a hidden input field
<button type=“submit”>Submit</button>
</form>
In API areas for the websites in which we will have our requests fully authenticated, the
CSRF should be disabled. API routing can be ignored by the use of routers and Express.
Consider the example given below, which shows how this can be done:
// parsing cookies
application.use(cParser())
// mounting the api before the csrf is appended to our app stack
application.use(‘/api’, api)
appliation.use(csrfProtection)
})
})
function createApiRouter() {
})
return router
That is how it can be done.
Custom error handling
When the validation of the CSRF has failed, an error with “err.code ===
messages. Consider the example given below, which shows how this can be done:
application.use(cParser())
res.status(403)
res.send(‘ The form was tampered with’)
})
This is the Node.js middleware for body parsing. However, it does not handle multipart
bodies because of their large and complex nature. When dealing with multipart bodies,
multer
formidable
To install it, just execute the following command:
To use the API, include it in your program by use of the “require” command. This is
shown below:
With the object “bParser,” various factories are exposed for the purpose of creation of
middlewares. The property “req.body” will be populated by all middlewares by use of the
parsed body or an error will be parsed to the callback.
simple example given below, which shows how this can be done:
application.use(bParser.json())
res.setHeader(‘Content-Type’, ‘text/plain’)
res.write(‘you posted:\n’)
})
express route-specific
Body parsers can be added to the routes which need them. This is possible in Express and
it can easily be done. This is the most easy and recommended way that the body-parser
can be used in Express. Consider the example given below, which shows how this can be
done:
res.send(‘welcome, ‘ + req.body.username)
})
})
Changing the content type for parsers
With all parsers, a type option is accepted and with this, the content-type will be
changeable and this should be the one to be parsed by the middleware. Consider the
This is the simplest manner in which Express can be implemented. To install it, execute
the following command:
npm i flash
Consider the example given below, which shows how this can be done:
application.use(require(‘flash’)());
// flashing a message
next();
})
Consider the second example given below:
a.alert(class=‘alert-‘ + msge.type)
p= message.msge
while msge = flash.shift() // consuming the messages as jade has read them
a.alert(class=‘alert-‘ + msge.type)
p= message.msge
An array of f
{
“type”: “info”,
“message”: “message”
method-override
This is used for overriding HTTP verbs. With it, one can use HTTP verbs such as
“DELETE” and “PUT” in places where they are not supported by the client. To install it in
For this module to be used, you have to know that a bit has to be used before any of the
For the header to be used for overriding, the header name has to be specified as a string
argument to the function “methodOverride,” For the call to be made, the POST request has
to be sent to the URL having the header as the overridden method. Consider the example
application.use(mthdOverride(‘X-HTTP-Method-Override’))
Consider the example given below, which shows how this can be used with
“XMLHttpRequest”:
c.onload = onload
c.send()
function onload() {
}
Chapter 13- serve-favicon
This is a Node.js middleware which is used for the purpose of serving favicons. A favicon
is just a visual cue which browsers and other client software use for the purpose of
identifying a site.
The module can be installed into the system by executing the following command:
Consider the example given below, showing how this can be used in express:
application.use(favicon(__dirname + ‘/public/favicon.ico’));
application.use(favicon(__dirname + ‘/public/favicon.ico’));
application.listen(3000);
This is a type of middleware which can be used everywhere, including outside Express
and connect.
res.statusCode = 404;
res.end(‘hello’);
});
});
server.listen(3000);
Chapter 14- response-time
This is the node.js response time header. It works by creating a middleware for recording
the response time of its requests in the HTTP servers. The response time in this case will
be the time when the request has entered the middleware to the time when the headers
The module can be included into the program by use of the “require” keyword as shown
below:
Consider the example given below, which shows how this can be used in both the Express
and the connect:
application.use(respTime())
res.send(‘hello, there!’)
})
res.setHeader(‘content-type’, ‘text/plain’)
res.end(‘hello, there!’)
})
})
console.error(err.stack)
})
.replace(/[:.]/g, ”)
.replace(/\//g, ‘_’)
statistics.timing(stat, time)
}))
res.send(‘hello, there!’)
})
Chapter 15- express-namespace
With this, namespaced routing capabilities are added to Express. To install it into the
system, one can execute the following command:
Consider the example given below, which can be used for responding to any of the
GET /forum/12
GET /forum/12/view
GET /forum/12/edit
GET /forum/12/thread/5
DELETE /forum/12
For the module to be used, one must use the “app.namespace()” and “require(‘express-
namespace’).” The module will then be made available to you.
To use it, we have to pass a callback function, and then perform a routing to the method.
After each of the callbacks, the invocation will be completed, and the namespace will be
stored together with its state. This is shown below:
application.namespace(‘/forum/:id’, function(){
});
});
application.namespace(‘/thread’, function(){
});
});
});
});
The current namespace can also be accessed via the “app.currentNamespace.” You should
also know how to run the tests. However, before doing this, make sure that you have all of
the sub-modules installed into the system. These can be installed by executing the
following command:
$ make test
This is used for exposing the objects, functions, and raw js to the client side. This feature
is good for sharing of settings, utils, and the current data for the user. The helpers and the
application = expose(application);
application.expose(…);
The above is how the module can be used in express 4.x. In express 2.x and 3.x, it can be
done as follows:
application.expose(…);
How to express the objects
One way that objects can be exposed to the client side is by exposing the properties, and
most probably the Express configuration. When the “app.expose(object)” is exposed, the
properties will be exposed to the “application.*” The example given below shows how
application.expose(application.settings);
Helper methods can also be exposed by another use case. This can be in the same way that
you are currently exposing. This is shown below:
script!= javascript
A named function can easily be exposed. You only have to pass it with a default name for
the buffer to replace it with a template name. An example of this is shown below:
application.expose(function someFunction(){
return ‘yes’;
}, ‘foot’);
An anonymous function can also be passed, and this will execute itself so as to create a
wrapper function. Consider the example given below, which shows how this can be done:
application.expose(function(){
function notify() {
notify();
});
All the above which has been discussed can be applied to the request-level. Consider the
res.expose(user, ‘application.current.user’);
});
Chapter 17- connect-render
This is a helper for the template render in connect. It can be installed by executing the
following command:
render({
layout: ‘layout.html’,
helpers: {
})
);
});
application.listen(8080);
/**
* Use case:
*
* var render = require(‘connect-render’);
* connect(
* render({
* open: “<%”,
* helpers: {
* config: config,
* },
* }
* });
* );
* // no layout
*/
function middleware(options) {}
Conclusion
features which developers can take advantage of so as to create their applications. It works
by use of its middleware. The framework also provides developers with numerous
modules which they can use for the development of their applications.
Each of these modules has its own command which can be used for its installation. To use
of any of its modules, you have to begin by installing it. It supports the use of sessions
which are very useful in the creation of web applications. It has a variety of options which
you can use for the purpose of development. You should learn how to use the different
options which are available for each ExpressJS module. The serve-index module is used
This is very interesting in development. With the “cookie-sessions” module, one can
provide guest sessions so that each of the visitors will have a session, whether
authenticated or not. This is also one of the best and interesting features in Express. This
Node framework is very easy to learn even for beginners. This book helps you in learning
how to use it.