Search icon CANCEL
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
$54.99
Subscription
Free Trial
Renews at $19.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
Table of content icon View table of contents Preview book icon Preview Book

Express Web Application Development

Chapter 2. Your First Express App

This chapter is about understanding the core structural and functional aspects of an Express app. We will start with a very basic app and proceed to make it gradually more complex by introducing the components of a relatively advanced Express app one after another.

This chapter is essential to develop a very good understanding of what an Express app is made up of, and how it works.

You will learn the following in this chapter:

  • How to create a very basic Express app

  • How to define basic routes and handle them

  • How to use views

  • How to include CSS, JavaScript, and images in the app

  • How to use middleware

  • How to include Node modules in the app

  • How to log requests to the app

  • How to configure the app

  • How to run the app in different modes

Your first Express app


The best way to learn any new technology is to try it out using some practical examples. So, let's go ahead and build an Express app and find out how it works.

To ensure our experiments do not mess up our filesystem, let's create a directory named express-app in your home directory and build our app there:

$ cd ~
$ mkdir express-app
$ cd express-app

The app directory is ready and we can start building our first Express app.

The Express manifest file

In Chapter 1, What is Express?, we learned that Express apps are actually Node modules, which means our app also would need a manifest file. So, create a file named package.json in the app directory.

The package.json file can have more than a dozen fields, but for the sake for brevity, let's keep it minimal. Here is what it should look like:

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

The fields used...

Auto-generating an Express app


The process of creating the manifest file, the app.js file, the views, and other directories and files can become a tedious chore as we start to work on multiple projects. To automate this process, we can use the express command-line tool.

To refresh you memory, we first encountered the express command-line tool while learning how to install Express. We were told that it generates Express app skeletons; now we have a fairly good idea what it might do.

Using its help option (-h), let's ask express how it works and what its options are:

$ express –h

  Usage: express [options] [directory]

  Options:

    -h, --help          output usage information
    -V, --version       output the version number
    -s, --sessions      add session support
    -e, --ejs           add ejs engine support (defaults to jade)
    -J, --jshtml        add jshtml engine support (defaults to jade)
    -H, --hogan         add hogan.js engine support
    -c, --css <engine>  add stylesheet...

Empowering Express with middlewares


In Chapter 1, What is Express?, we learned about Express middlewares and saw how to create one. Now, let's go find out how to include one in our app. Remember we use app.use() for including middlewares.

Though we can write our own middlewares, we will focus on using one of the middlewares that comes bundled with Express.

For your reference, the following is the list of the middlewares that are available in Express, by default:

Middleware

Description

router

The app's routing system

logger

Log requests to the server

compress

gzip/deflate support on the server

basicAuth

Basic HTTP authentication

json

Parse application/ json

urlencoded

Parse application/x-www-form-urlencoded

multipart

Parse multipart/form-data

bodyParser

Parse request body. Bundles json, urlencoded, and multipart middlewares together

timeout

Request timeout

cookieParser

Cookie parser

session

Session support

cookieSession

Cookie-based...

Empowering Express with Node modules


Express does not come packed with a huge bunch of built-in libraries to perform tasks that are beyond a basic website. Express is very minimal. But that does not mean that it is not capable of performing complex tasks.

You have a huge collection of Node modules on the npm registry that can be easily plugged in to your app and used for performing all sorts of tasks in the app.

In Chapter 1, What is Express?, we were introduced to Node modules, and we learned how to write them. We also found out that they can be used to modularly extend the power and capability of Express.

You could write your own Node modules to accomplish many things, but anything you are trying to achieve, probably there is an excellent open source Node module out there already. You just need to find the right module, install it, and use it in your app.

Note

The npm registry/network in a publicly available online resource where Node developers publish their Node modules. These modules are...

Logging requests to the App


Express comes with a built-in logging module called logger, it can be a very useful tool while you are developing the app. You enable it like any other Express module:

app.use(express.logger());

Without any options, the logger middleware will log a detailed log. You can customize the details with the following tokens in the format option of the logger middleware:

Token

Content

:req[header]

The specific HTTP header of the request

:res[header]

The specific HTTP header of the response

:http-version

The HTTP version

:response-time

How long it took to generate the response

:remote-addr

The user agent's IP address

:date

Date and time of request

:method

The HTTP method used for making the request

:url

The requested URL

:referrer

The URL that referred the current URL

:user-agent

The user-agent signature

:status

The HTTP status

And this is how you specify the log format using the tokens:

app.use(express.logger({ format: ':remote...

Using a configuration file


We actually don't need to use an .ini file for configuring our apps, as shown in a previous example. The purpose of the example was just to show you how to use a Node module, not the recommended practice.

As a side effect of how require() works, Node supports JSON-based configuration files by default. Create a file with a JSON object describing the configurations, save it with a .json extension, and then load it in the app file using require().

Note

It is important to ensure that the file extension is .json and the JSON object confirms to the JSON specification, or else it will throw an error.

Here is an example of a JSON-based config file:

{
  "development": {
    "db_host": "localhost",
    "db_user": "root",
    "db_pass": "root"
  },

  "production": {
    "db_host": "192.168.1.9",
    "db_user": "myappdb",
    "db_pass": "!p4ssw0rd#"
  }
}

This is how you would load it:

var config = require('./config.json')[app.get('env')];

Now the environment-specific configuration...

Setting and getting application options


An Express application has a set of predefined application variables that are used to configure various options of the app. These variables are used for setting various dynamic aspects of the app and can be set using the app.set() method. So far we have used two of them:

app.set('view engine', 'jade');
app.set('views', './views');

The values of application variables can be retrieved using the corresponding app.get() method.

The following table lists all the options that can be configured in an Express app:

Option

Purpose

env

The environment the app is running on. Not recommended to set manually. You will read more about this in the next section.

trust proxy

Enables reverse proxy.

jsonp callback name

Callback name for JSONP requests.

json replacer

The JSON replacer callback.

json spaces

The amount of space for indenting JSON responses.

case sensitive routing

Makes route names case-sensitive.

strict routing

Trailing slash at...

Express in different environments


In a software release process, we designate systems for development, UAT, staging, production, and so on for different stages of product release. Technically, these contexts of application execution are called environments.

It is very common that we want our software to execute differently on different environments. For example, in a development environment, we would like to see a very verbose detail about any error our software might encounter, but we might not want to do so in the production environment. Express has a very simple mechanism to let us do that. Let's find out how it works.

Express' app.get('env') method returns the current environment of the app. Based on this value, you can configure your app to use different middlewares, Node modules, and so on; effectively changing the behavior of the app based on the environment.

Before we go about configuring our app based on its environment, let's find out how app.get('env') works.

When an Express app starts...

Summary


In this chapter, we learned how to create a fairly complete Express app from the ground up. We started by demonstrating the fact that Express are Node modules. Then we went on to create a simple app, upon which we added more and more components and features to make it more complex. By the end of the exercise, we had an app that could run on different modes depending on the environment.

We now have a good amount of knowledge to make sense of an auto-generated Express app.

Since routes are the public interfaces to an app, they make it a natural topic to focus on next. We will learn in detail about routes in Express in the next chapter.

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

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
$19.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
$199.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
$279.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 $ 147.97
Express Web Application Development
$54.99
Node Web Development - Second Edition
$48.99
Advanced Express Web Application Development
$43.99
Total $ 147.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.