Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Express Web Application Development
Express Web Application Development

Express Web Application Development: Here's a comprehensive guide to making the most of Express's flexibility in building web applications. With lots of screenshots and examples, it's the perfect step-by-step manual for those with an intermediate knowledge of JavaScript.

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Express Web Application Development

Chapter 1. What is Express?

This chapter is a beginner-friendly introduction to Express. Along with the basics, you will learn about the core concepts and components that make up an Express app. While we won't be doing a lot of coding in this time, the chapter will orient and condition you to Express, which will prepare you for the upcoming chapters.

Do not skip this chapter, the material covered here provide the map and compass to your journey of learning Express.

What is Express?


Express is a minimal yet flexible and powerful web development framework for the Node.js (Node) platform.

What do we mean by minimal yet flexible and powerful?

Express is minimal because it does not come loaded with all sorts of functionality, which makes it a bloat-free framework. Out of the box, it supports only the very basic features of a web framework. Even the supported features are not all enabled by default, you have the option to pick and use, according to your needs.

The flexibility in Express comes from the use of middlewares and Node modules. Express middlewares and Node modules are pluggable JavaScript components, which make Express apps very modular, flexible, and extensible.

Express is a powerful framework because it gives you complete access to the core Node APIs. Anything you can do with Node, you can do it with Express too.

Express can be used to create very simple to very complex web apps. It provides you all the tools required to create the most complex of apps, but does not force you to use them when you don't need them.

Hearing someone tell you that Express is a minimal, flexible, and powerful web development framework doesn't really help much in understanding it, does it?. Many other frameworks probably claim the same thing. Let's find out what is actually special about Express.

The story of Express

There is an interesting story behind the origin of Express. You will understand Express better if you know the story, so let me share the story of how Express came into being.

Sometime in February 2009, Ryan Dahl had an epiphany about combining JavaScript and Google's V8 engine to create a new system-level programming platform. He christened the platform as Node.js (Node), and released v0.0.1 in the same month.

Node was very well received by the web development community, and it started to grow very rapidly in popularity.

Apart from being a general-purpose software development platform, Node provided a web server API (Application Programming Interface), using which developers could create web apps using JavaScript as the backend programming language.

However, there was a problem with Node's web server API: It was a little too low level, and you had to write and re-write many of the web server functions in your web apps. Modularity and extensibility became a problem for any project that was even moderately big.

Within five months of Node's release, in June 2009, T.J. Holowaychuk, released an open source project named Express to make web development a little easier in Node.

Express was inspired by Ruby's Sinatra and built on top of Node's web server API. It was a little crude, but provided some of the niceties—such as a routing system, session and cookie support, MIME helpers, RESTful interface, HAML-based views, and so on—one might expect from a web development framework.

However, Express v0.0.1 was very different from what Express 3 is today. Perhaps, the only thing common in between them is the name "Express".

In June 2010, Sencha, under its Sencha Labs, started an open source project named Connect, to solve the modularity and extensibility issue in the Node web server API. The project was inspired by Ruby's Rack web server interface. Tim Caswell, a Sencha employee, and T.J. Holowaychuk, were roped in to lead the project.

Like Express, Connect was also built on top of Node's web server API, and came with a middleware system, which allowed small re-usable programs to be plugged onto it to handle HTTP-specific functionalities.

Connect middlewares took care of many of the commonly required functionalities in web apps for Node. On top of that, anyone could write their own middleware for their apps. Connect considerably improved the modularity and extensibility of the Node web server API.

By now, there were two different web development frameworks for Node: Express and Connect—one was inspired by Sinatra, and the other by Rack. This caused a bit of confusion in the Node community, especially with Holowaychuk working on both of them.

But as luck would have it, it became obvious that Express and Connect were actually complementary frameworks. So, in July 2010, Holowaychuk decided to re-architect Express to run on top of Connect, effectively merging Connect with Express to create a new incarnation of Express in v1.0.0.

With Express v1.0.0, there was no more confusion about which web development framework to choose in Node. Express was Connect with additional functionalities built on top of it. To this day it remains the same—Express continues to use the Connect middleware, and any change in Connect is invariably reflected in Express.

So, that is the story of how Express came into being and how Connect is related to it.

As an Express developer, you might rarely deal with Connect directly, but you will be using a lot of middlewares in your projects. Middlewares in Express are referred to as Express middlewares and not Connect middlewares, although technically they are Connect middlewares. You will learn more about middlewares in upcoming sections in this and the next chapter.

Installing Express


Installing Express is pretty straightforward, especially if you have Node installed already. Even if you don't have Node installed, you need not worry, because I will show you how to install Express from scratch, and that includes installing Node.

If you are on a Windows or Mac machine, installing Node is very easy—just download the respective installer from http://nodejs.org/download/. On Linux machines, the installation process is a little more elaborate. I will show you how to install Node on an Ubuntu machine.

Note

For a relatively easier and cleaner installation of Node, you can use Node Version Manager (nvm). Besides installing Node, it will help you flexibly switch to any version of Node right on your machine. Read more about nvm at https://github.com/creationix/nvm.

Before we go about installing Node, let's make sure we have the required dependencies on the system by executing the following command:

$ sudo apt-get -y install build-essential g++ libssl-devpkg-config

With that, we are ready to start installing Node. Let's get the source code from the Node download page located at http://nodejs.org/download/. At the time of writing, the source code was located at http://nodejs.org/dist/v0.10.7/node-v0.10.7.tar.gz. Let's download the source code archive to the /tmp directory and install Node from there:

$ cd /tmp
$ wget http://nodejs.org/dist/v0.10.7/node-v0.10.7.tar.gz
$ tar zxvf node-v0.10.7.tar.gz
$ cd node-v0.10.7
$ ./configure
$ make
$ sudo make install

If everything went fine, you have Node installed on your system now. Let's confirm it with a quick Node version check command:

$ node -v
> v0.10.7

Congratulations! Let's go install Express now.

As I mentioned earlier, installing Express is very straightforward once you have Node installed on your system.

Express is a Node module, and like any other Node module, it is installed using the Node Package Manager (npm), which comes installed with Node by default. You will learn more about npm and Node modules in a later section.

Node modules come in two variants: local and global. Local modules are meant to be used in a specific project, and are available only for that particular project, while global modules are installed system-wide, and are almost always available as a command-line tool.

Express is meant to be installed as a global module, so that we can use its express command-line tool to generate Express app skeletons quickly.

Note

Express is the web development framework. express is the command-line tool to create Express app skeletons.

We specify the -g option in the npm install command to install Node modules as global modules. Here is the command to install Express:

$ sudo npm install express -g

That command will install the latest stable version of Express. In case, you want to install a specific version of Express, you can specify the version using the @ parameter in the module name. Here is an example of installing an older version of Express:

$ sudo npm install express@3.0.5 -g

After the installation process is complete, confirm you are able to execute the express command, with a version check:

$ express –V
> 3.2.6

Congrats! Your system is ready for Express development now.

The stuff that makes up Express


A good thing about Express is that there are only three core components to it, which makes it relatively easy to know a lot about Express, if not master it entirely. In this section, I will give a brief introduction about each of the core Express components, so that you are not left disoriented when you come across them in the coming chapters.

The application object

The application object is an instance of Express, conventionally represented by the variable named app. This is the main object of your Express app and the bulk of the functionality is built on it.

This is how you create an instance of the Express module:

var express = require('express');
var app = new express();

The following is a brief description of all the properties and methods available on the application object:

Property/Method

Description

app.set(name, value)

Sets app- specific properties

app.get(name)

Retrieves value set by app.set()

app.enable(name)

Enables a setting in the app

app.disable(name)

Disables a setting in the app

app.enabled(name)

Checks if a setting is enabled

app.disabled(name)

Checks if a setting is disabled

app.configure([env], callback)

Sets app settings conditionally based on the development environment

app.use([path], function)

Loads a middleware in the app

app.engine(ext, callback)

Registers a template engine for the app

app.param([name], callback)

Adds logic to route parameters

app.VERB(path, [callback...], callback)

Defines routes and handlers based on HTTP verbs

app.all(path, [callback...], callback)

Defines routes and handlers for all HTTP verbs

app.locals

The object to store variables accessible from any view

app.render(view, [options], callback)

Renders view from the app

app.routes

A list of routes defined in the app

app.listen()

Binds and listen for connections

The request object

The HTTP request object is created when a client makes a request to the Express app. The object is conventionally represented by a variable named req, which contains a number of properties and methods related to the current request.

The following table lists all the properties and methods of the req object and provides a brief description of them:

Property/Method

Description

req.params

Holds the values of named routes parameters

req.params(name)

Returns the value of a parameter from named routes or GET params or POST params

req.query

Holds the values of a GET form submission

req.body

Holds the values of a POST form submission

req.files

Holds the files uploaded via a form

req.route

Provides details about the current matched route

req.cookies

Cookie values

req.signedCookies

Signed cookie values

req.get(header)

Gets the request HTTP header

req.accepts(types)

Checks if the client accepts the media types

req.accepted

A list of accepted media types by the client

req.is(type)

Checks if the incoming request is of the particular media type

req.ip

The IP address of the client

req.ips

The IP address of the client, along with that of the proxies it is connected through

req.path

The request path

req.host

Hostname from the HTTP header

req.fresh

Checks if the request is still fresh

req.stale

Checks if the request is stale

req.xhr

Checks if the request came via an AJAX request

req.protocol

The protocol used for making the request

req.secure

Checks if it is a secure connection

req.subdomains

Subdomains of the host domain name

req.url

The request path, along with any query parameters

req.originalUrl

Used as a backup for req.url

req.acceptedLanguages

A list of accepted languages by the client

req.acceptsLanguage(langauge)

Checks if the client accepts the language

req.acceptedCharsets

A list of accepted charsets by the client

req.acceptsCharsets(charset)

Checks if the client accepts the charset

The response object

The response object is created along with the request object, and is conventionally represented by a variable named res. While it may sound a little strange that both of them should be created together, it is a necessity to give all the middlewares a chance to work on the request and the response object, before passing the control to the next middleware.

The following is a table of properties and methods on the response object:

Property/Method

Description

res.status(code)

Sets the HTTP response code

res.set(field, [value])

Sets response HTTP headers

res.get(header)

Gets the response HTTP header

res.cookie(name, value, [options])

Sets cookie on the client

res.clearCookie(name, [options])

Deletes cookie on the client

res.redirect([status], url)

Redirects the client to a URL, with an optional HTTP status code

res.location

The location value of the response HTTP header

res.charset

The charset value of the response HTTP header

res.send([body|status], [body])

Sends an HTTP response object, with an optional HTTP response code

res.json([status|body], [body])

Sends a JSON object for HTTP response, along with an optional HTTP response code

res.jsonp([status|body], [body])

Sends a JSON object for HTTP response with JSONP support, along with an optional HTTP response code

res.type(type)

Sets the media type HTTP response header

res.format(object)

Sends a response conditionally, based on the request HTTP Accept header

res.attachment([filename])

Sets response HTTP header Content-Disposition to attachment

res.sendfile(path, [options], [callback]])

Sends a file to the client

res.download(path, [filename], [callback])

Prompts the client to download a file

res.links(links)

Sets the HTTP Links header

res.locals

The object to store variables specific to the view rendering a request

res.render(view, [locals], callback)

Renders a view

Concepts used in Express


There are a few concepts you should be familiar with before you start developing in Express. It is important that you know them, because you will be able to come up with creative and effective solutions to the challenges you might face in your projects, if you are familiar with them.

These concepts will help you understand Express better, which means more power and control to you.

Asynchronous JavaScript

Many beginners in JavaScript get stumped while using Node for the first time because they are not familiar with asynchronous (async) JavaScript and callback functions (callbacks). Node and Express are built on the concept of async operations, so it is imperative that you understand the concept before you proceed any further.

Note

If you have used AJAX in its default state, you are already familiar with asynchronous JavaScript. On the client-side, AJAX and timer functions are the only obvious instances where you get to see JavaScript in async mode. On Node, they are all over the place.

Unlike the more common synchronous functions, asynchronous functions do not return immediately; at the same time they do not block the execution of its succeeding code. This means other tasks are not piled up waiting for the current task to be completed. However, to resume control from the async operation and to handle its result, we need to use a callback function. The callback function is passed to the async function to be executed after the async function is done with its job.

Here is an example of using a timer to illustrate how callbacks work:

var broadcast = function(msg, timeout, callback) {

  // initiate an async call using a timer
  setTimeout(function() {
    // the first message
    console.log(msg);
    // execute the callback function
    callback();
  }, timeout);
};

broadcast('Is there anybody out there?', 1000, function() {
  console.log('Message sent');
});

We passed in a callback to the broadcast function, which will be executed after the message is "broadcasted" after one second.

Though Node is synonymous with async operations, it still provides a sync alternative to many of its operations. However, it is recommended to stick to the async versions, else you will very likely lose the non-blocking advantage of Node.

Node modules

A Node module is a JavaScript library that can be modularly included in Node applications using the require() function. What the module is capable of is entirely dependent on the module—it can be simple helper functions to something more complex such as a web development framework, which is what Express is.

If you have used npm to install something, you have used a node module. A lot of them are installed as command-line tools, such as the express command. A lot more of them are installed as libraries to be used with a Node program.

Note

npm is a command-line tool for installing Node modules. It comes installed with Node by default. Type npm help at the command line to see its various options and commands.

The official website of npm is located at https://npmjs.org/, and you can find a huge list of Node modules at https://github.com/joyent/node/wiki/modules.

The bulk of web server-related functionality in Express is provided by its built-in middlewares. Features not supported by Express out of the box are implemented using Node modules.

Since Express provides just the bare minimum functionality of a web server, it does not support some common but crucial functionality, such as connecting to a database, sending e-mails, and so on. In such cases, you will need to find and install the appropriate Node modules and use them to get your task done.

The fact that Express does not come baked in with opinionated modules or methods to accomplish tasks beyond handling HTTP requests is a good thing, because it keeps the framework bloat-free and gives its users the freedom of choice to use any module or method according to their specific requirements.

The Node community is very active and has developed modules for almost every requirement on a typical web project. So remember, if you are looking to do something tricky or complex, probably there is a Node module for it already, if it does not exist, probably you should create it and share it with the Node community. If you are in no mood for sharing with others, make it a private Node module and keep it to yourself.

If it makes you wonder what is the difference between a public and a private module: public modules can be published on the npm registry and installed by the general public, whereas private modules remain private.

As you start working with Express, you will realize that writing your own modules will greatly help in modularizing your app. So, it is essential that you learn how to write them.

There are two approaches to writing Node modules: one involves attaching properties and functions to the exports object, the other involves assigning JavaScript objects to the module.exports property of a module.

The attachment to exports approach is pretty straightforward, as you can see from the following example:

var name = exports.name = 'Packt';
var secret = 'zoltan';

exports.lower = function(input) {
  return input.toLowerCase();
};

exports.upper = function(input) {
  return input.toUpperCase();
};

exports.get_name = function() {
  return name;
}

exports.get_secret = function() {
  return secret;
}

Anything attached to the exports objects is available as a public property or method of the instance of the module. Any variable defined with the var keyword and not attached to the exports object becomes a private variable of the module. Save the preceding example code in a file named mymod.js, and include it in a file named test.js with the following code:

var mod = require('./mymod.js');

console.log(mod.name);
console.log(mod.lower('APPLE'));
console.log(mod.upper('mango'));
console.log(mod.get_name());

Execute test.js to see the module in action:

$ node test.js
Packt
apple
MANGO
Packt

The assignment to module.exports approach is straightforward too. If you were to implement the previous module using the assignment method, this is how it would look like:

var secret = 'zoltan';

module.exports = {

  name: 'Packt',

  lower: function(input) {
    return input.toLowerCase();
  },

  upper: function(input) {
    return input.toUpperCase();
  },

  get_name: function() {
    return this.name;
  },

  get_secret: function() {
    return secret;
  }
  
};

There is an interesting thing about the second method of writing Node modules: you can assign any valid JavaScript object to the module.exports property, and it becomes the module. In the following example, we assign a function to the module.exports property:

module.exports = function(word) {
  
  var reversed = '';
  
  var i = word.length - 1;
  while (i> -1) {
    var letter = word[i];
    reversed += letter;
    i--;
  }
  
  return reversed;
};

Save the preceding code in a file named reverse.js. You can include it in the test.js file and use if for reversing text:

var reverse  = require('./reverse.js');
console.log(reverse('hippopotamus'));

Execute test.js again to see reverse.js in action:

$ node test.js
sumatopoppih

Using the assignment method, you can create Node modules to be of any valid JavaScript object type.

If you ever happen to have both the attachment and assignment methods defined in the same module file, the assignment method will take precedence.

Express apps are Node modules

It might sound a little strange, but every Express app is also a Node module. You might rarely use your web app like a regular Node module and include them in other apps, but there is something which will be an indispensable part of your app—its manifest file, package.json.

Note

A manifest file is a file which contains meta data about some software. The content of the file may be used by the software to customize itself.

Node modules come with a manifest file named package.json, which contains details, such as its name, version, dependencies, and so on about the module.

Note

Node modules, such as Express, which come with a package.json file and can be installed using npm are formally called Node packages. However, we will use the terms modules and packages interchangeably in the book without getting too pedantic.

Here is an example of an Express app's package.json file:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app"
  },
  "dependencies": {
    "express": "3.2.6",
    "jade": "*",
    "stylus": "*"
  }
}

Among the various fields, dependencies is what would be of your prime interest. For an interactive guide to all the possible fields in a package.json file, visit http://package.json.nodejitsu.com/.

Any time you install a Node module in the application directory, the module will get added to the dependencies list with the version you specified. Of course, you can manually make new entries or update the version numbers of existing dependencies if you want to.

You may wonder what is the point of adding the modules in the dependencies when you already are installing them using npm. Well, if you start using a version control system such as Git or SVN, it doesn't make sense to include the installed Node modules in the repository. However it makes sense to include the package.json file, because with a simple npm install command in the app directory, you can reinstall the dependencies in one go.

It is advisable to use all other fields of the package.json file, but you certainly can't do without the dependencies key, if you are serious about your app.

By convention, the main file of the Express app is named app.js. You can rename it to anything you want, but it is generally not recommended to do so.

Middlewares

A middleware is a JavaScript function to handle HTTP requests to an Express app. It can manipulate the request and the response objects or perform an isolated action, or terminate the request flow by sending a response to the client, or pass on the control to the next middleware.

Middlewares are loaded in an Express app using the app.use() method.

Following is an example of a middleware. All it does is print the IP address of the client that made the request. Although it may seem like a trivial middleware, it gives you a very good overview of how middlewares work:

app.use(function(req, res, next) {
  console.log('Request from: ' + req.ip);
  next();
});

As you can see, a middleware is just a function that accepts three parameters: req, res, and next. The req parameter is the request object, the res parameter is the response object, and the next parameter is a reference to the next middleware in line. Any middleware can end a request by sending a response back to the client using one of the response methods on the res object. Any middleware that does not call a response method must call the next middleware in line, else the request will be left hanging in there.

Even though our middleware in the previous example was pretty simple, in most practical cases, middlewares will be created in a more complex fashion—they could be a JavaScript object defined right in the file, or might be included as a Node module.

This is how a middleware would look like if it were defined first and then passed to the app.use() method:

// define the middleware
var forbidder = function(forbidden_day) {

  var days = ['Sunday', 'Monday', 'Tueday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  
  return function(req, res, next) {
    
    // get the current day
    var day = new Date().getDay();
    
    // check if the current day is the forbidden day
    if (days[day] === forbidden_day) {
      res.send('No visitors allowed on ' + forbidden_day + 's!');
    }
    // call the next middleware
    else {
      next();
    }
  }
};

// use the forbidder middleware
app.use(forbidder('Wednesday'));
// the router middleware goes here
app.use(app.router);

This middleware forbids visitors on your website on a certain day. Probably not a very useful middleware, but the intent is to show you how a middleware works.

One thing you might have noted is that we included the forbidder middleware before the router middleware. Does it make any difference? Oh yes, it does! A middleware included earlier takes precedence over those included later. So be careful about the order of inclusion.

If we were to rewrite the forbidder middleware as a Node module, we would need to first create the forbidder.js module file with the following content:

module.exports = function(forbidden_day) {

  var days = ['Sunday', 'Monday', 'Tueday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  
  return function(req, res, next) {
    
    // get the current day
    var day = new Date().getDay();
    
    // check if the current day is the forbidden day
    if (days[day] === forbidden_day) {
      res.send('No visitors allowed on ' + forbidden_day + 's!');
    }
    // call the next middleware
    else {
      next();
    }
  }
};

Then, the module would be included in the app, and an instance of the module would be created:

var forbidder = require('./forbidder.js');

And the middleware would be added to the chain:

app.use(forbidder('Wednesday'));

The majority of top-level Express functionality is implemented via its built-in middlewares. An indispensable component of Express is the router middleware, which is responsible for routing the HTTP requests to your Express apps to the appropriate handler functions.

Request flow

One might be tempted to think that when you make a request to your web app, there would be a corresponding JavaScript file that would be executed by Node. For example, to load the home page, there would be a file named home.js, for the contact page, contact.js, and so on.

That's not the case in an Express app. There is a single entry point for all the requests coming to the app—via app.js—which bootstraps the Express framework.

When an HTTP request arrives at your app, it goes through a stack of middlewares. All the middlewares in the chain have the capacity to modify the request and the response object in any form and manner, and that's how they work, as we learned in the last section.

Among the middlewares, which are include in Express, the most important is the router middleware, which gives Express the capability to define routes and handle them.

Here is a conceptualized representation of routes and their handlers:

The destinations of the HTTP request URIs are defined via routes in the app. Routes are how you tell your app "for this URI, execute this piece of JavaScript code". The corresponding JavaScript function for a route is called a route handler. It is the responsibility of the route handler to respond to an HTTP request, or pass it on to another handler function if it does not. Route handlers may be defined in the app.js file or loaded as a Node module.

Here is a working example of some routes and their handlers defined right in the app.js file:

var http = require('http');
var express = require('express');
var app = express();

app.get('/', function(req, res) {
  res.send('Welcome!');
});

app.get('/hello.text', function(req, res) {
  res.send('Hola!');
});

app.get('/contact', function(req, res) {
  res.render('contact');
});

http.createServer(app).listen(3000, function(){
  console.log('Express server listening on port ' + 3000);
});

Defining the routes and their handlers in the app.js file may work fine if the number of routes is relatively few. It becomes messy if the number of routes starts growing. That's where defining the routes and their handlers in a Node module comes in handy. If we were to modularize the routes we defined earlier, here is how it would look like.

Note

The reason I used a strange looking route /hello.text is to show that route names can be anything and have no inherent meaning in Express. It is up to the route handler to give meaning and purpose to the routes.

The following is the content of the routes.js Node module:

module.exports = function(app) {
  
  app.get('/', function(req, res) {
    // Send a plain text response
    res.send('Welcome!');
  });
  
  app.get('/hello.text', function(req, res) {
    // Send a plain text response
    res.send('Hola!');
  });
  
  app.get('/contact', function(req, res) {
    // Render a view
    res.render('contact');
  });
};

The modified app.js file would look like the following now:

var http = require('http');
var express = require('express');
var app = express();
var routes = require('./routes')(app);

http.createServer(app).listen(3000, function(){
  console.log('Express server listening on port ' + 3000);
});

A request handler can send a response back to the client using one of the response methods in the response object. The act of sending a response effectively terminates the request flow to any other route handler.

Views are special files in an Express app, which are sent as an HTML response after Express processes them. Express views support multiple layout and CSS preprocessor engines. In this book, we will focus on Jade for HTML and Stylus for CSS.

Node HTTP/HTTPS API

Express is built on top of Node's HTTP/HTTPS API. When one hears something like that, often it so happens that the underlying API is insulated by the framework, but it is not the case in Express. The Node HTTP/HTTPS API is very much accessible from the Express framework—the req and res objects are extensions of the req and res socket objects in a plain vanilla Node HTTP server.

So, anytime you feel the need to hack a little deeper, you can go ahead and work on the original Node objects and their properties and methods.

While we are at it, I would like to stress the point that not only is the HTTP/HTTPS API available for Express, but the whole of Node API is available from Express. Reading up the complete Node documentation will help you become a more efficient Express developer—you will understand the underlying mechanism better, write better middleware and modules for your apps, and have more control over the framework.

Note

Downloading the example code

You can download the example code fi les for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you

Summary


In this chapter, we learned about the core concepts and components in Express. We were also introduced to some example Express code, which prepared us for what we will be coming across in the coming chapters.

We now know what the omnipresent req, res, and next objects are in an Express application. We learned how to write middlewares and Node modules to extend the capability of our Express app. We are now ready get hands-on with a real Express app.

In the next chapter, we will get coding and create our first Express app. We will start from the very basics and learn about the various aspects that make up an Express app.

Left arrow icon Right arrow icon

Key benefits

  • Exploring all aspects of web development using the Express framework
  • Starts with the essentials
  • Expert tips and advice covering all Express topics

Description

Express is a minimal and flexible node.js web application framework, providing a robust set of features for building single and multi-page, and hybrid web applications. It provides a thin layer of features fundamental to any web application, without obscuring features that developers know and love in node.js. "Express Web Application Development" is a comprehensive guide for those looking to learn how to use the Express web framework for web application development. Starting with the initial setup of the Express web framework, "Express Web Application Development" helps you to understand the fundamentals of the framework. By the end of "Express Web Application Development", you will have acquired enough knowledge and skills to create production-ready Express apps. All of this is made possible by the incremental introduction of more advanced topics, starting from the very essentials. On the way to mastering Express for application development, we teach you the more advanced topics such as routes, views, middleware, forms, sessions, cookies and various other aspects of configuring an Express application. Jade; the recommended HTML template engine, and Stylus; the CSS pre-processor for Express, are covered in detail. Last, but definitely not least, Express Web Application Development also covers practices and setups that are required to make Express apps production-ready.

Who is this book for?

If you are looking to use Express to build your next web application, "Express Web Application Development" will help you get started and take you right through to Express' advanced features. You will need to have an intermediate knowledge of JavaScript to get the most out of this book.

What you will learn

  • Understand the core concepts and objects that make up the Express framework and an Express app
  • Create Jade-based views for Express apps and render them
  • Create routes for an Express app and handle them
  • Serve different kinds of responses and handle various kinds of errors
  • Create dynamic apps using HTML forms, cookies, and sessions
  • Learn about the Jade HTML templating language in detail
  • Learn about the Stylus CSS pre-processor syntax and language in detail
  • Customize and prepare your Express apps to make them production ready

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 25, 2013
Length: 236 pages
Edition : 1st
Language : English
ISBN-13 : 9781849696555
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 25, 2013
Length: 236 pages
Edition : 1st
Language : English
ISBN-13 : 9781849696555
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 112.97
Express Web Application Development
€41.99
Node Web Development - Second Edition
€37.99
Advanced Express Web Application Development
€32.99
Total 112.97 Stars icon

Table of Contents

8 Chapters
What is Express? Chevron down icon Chevron up icon
Your First Express App Chevron down icon Chevron up icon
Understanding Express Routes Chevron down icon Chevron up icon
Response From the Server Chevron down icon Chevron up icon
The Jade Templating Language Chevron down icon Chevron up icon
The Stylus CSS Preprocessor Chevron down icon Chevron up icon
Forms, Cookies, and Sessions Chevron down icon Chevron up icon
Express in Production Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(11 Ratings)
5 star 81.8%
4 star 9.1%
3 star 0%
2 star 9.1%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Gertraud Wilms-Hemmer Oct 07, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Das Buch habe ich gewählt wegen des Themenbereiches Echtzeit und weil es die Erklärung einer neueren Software-Technologie (node.js) verspricht, inklusive dessen Installation. Ich bewerte das Buch uneingeschränkt positiv wegen der guten, ausführlichen Erklärungen ohne überflüssigen Ballast. Positiv ferner: Den Quellcode kann man sich per E-Mail zuschicken lassen. Die dargestellten Beispiele laufen sofort. Vorkenntnisse in einer Programmiersprache, am besten JavaScript, sollten beim Leser vorhanden sein.
Amazon Verified review Amazon
yauh Sep 07, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have learned node.js and express on my own in building web and mobile apps. While it's ok to pick up different pieces of info from different websites and forums about node and express, it is much better to start with a beginner book like this one.Upon reading the book, I rounded out my knowledge with the author's clear technical explanations. It is a much welcome review of the important concepts. I would have had a much easier time if I were to learn from scratch with this book.High recommended for beginners trying to pick up node.js and express, and for people with practical experience but need a refresher.Much like express which is a concise framework doing the core things right, this book succinctly explains the core concepts to help developers get started. The clean explanations are also accompanied with working code samples.
Amazon Verified review Amazon
Wilson Oct 11, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I really have to admit the writer has a talent for writing technical books. I didn't find any resource or book that covers express.js in a lot of detail and explaining in interesting way.
Amazon Verified review Amazon
Nam Nguyen Sep 16, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you are looking for a good Express.js book, this is the one you should read. Certainly this book teaches me Express.js, from basic to advanced techniques. It has clear technical explanations. I like this book a lot because the author actually walks you through actual processes by teaching you what you should, should not do, how to organize all your projects, how to use configurations in your app. This is very important because after a certain level of complexity in your app, you will need to organize your routes.The last three chapters are the best, it actually shows you how to make your app production-ready such as how to benchmark your app using siege command, how to make your app scale and performance well using cluster module, how to ensure maximum uptime for the app, and how to handle critical events.I also recently found out that the author has a forum at [...] so you can post your questions. I did posted some questions and was able to get answers quickly
Amazon Verified review Amazon
Simos Aug 26, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It is a great book to read for anyone willing to get to know hot to create an express app. It is perfectly suited to developers with no prior knowledge on Node.js because is very explanatory and is moving forward step-by-step, helping the reader to follow at all steps. It enlightens the reader for some basic aspects of how to use Node.js, and at the same time guides the less-experienced developers on adding commonly used functionality for web apps. What i liked most on this book was the last chapter which goes through some much-needed modules and techniques that are almost mandatory for every Node.js app.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.