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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to South Africa

Standard delivery 10 - 13 business days

$12.95

Premium delivery 3 - 6 business days

$34.95
(Includes tracking information)

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 : 9781849696548
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
Estimated delivery fee Deliver to South Africa

Standard delivery 10 - 13 business days

$12.95

Premium delivery 3 - 6 business days

$34.95
(Includes tracking information)

Product Details

Publication date : Jun 25, 2013
Length: 236 pages
Edition : 1st
Language : English
ISBN-13 : 9781849696548
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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela