Express Js Documentation with PDF

 ExpressJS is a web application framework that provides you with a simple API to build websites, web apps and back ends. With ExpressJS, you need not worry about low level protocols, processes, etc.

What is Express?

Express provides a minimal interface to build our applications. It provides us the tools that are required to build our app. It is flexible as there are numerous modules available on npm, which can be directly plugged into Express.

Express was developed by TJ Holowaychuk and is maintained by the Node.js foundation and numerous open source contributors.

Why Express?

Unlike its competitors like Rails and Django, which have an opinionated way of building applications, Express has no "best way" to do something. It is very flexible and pluggable.

Pug

Pug (earlier known as Jade) is a terse language for writing HTML templates. It −

  • Produces HTML
  • Supports dynamic code
  • Supports reusability (DRY)

It is one of the most popular template language used with Express.

MongoDB and Mongoose

MongoDB is an open-source, document database designed for ease of development and scaling. This database is also used to store data.

Mongoose is a client API for node.js which makes it easy to access our database from our Express application.

ExpressJS - Environment

In this chapter, we will learn how to start developing and using the Express Framework. To start with, you should have the Node and the npm (node package manager) installed. If you don’t already have these, go to the Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal.

node --version
npm --version

You should get an output similar to the following.

v5.0.0
3.5.2

Now that we have Node and npm set up, let us understand what npm is and how to use it.

Node Package Manager(npm)

npm is the package manager for node. The npm Registry is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript community. npm allows us to access all these packages and install them locally. You can browse through the list of packages available on npm at npmJS.

How to use npm?

There are two ways to install a package using npm: globally and locally.

  • Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code.

npm install -g <package-name>
  • Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag.

npm install <package-name>

Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project.

Step 1 − Start your terminal/cmd, create a new folder named hello-world and cd (create directory) into it −

npm init info

Step 2 − Now to create the package.json file using npm, use the following code.

npm init

It will ask you for the following information.

npm init info

Just keep pressing enter, and enter your name at the “author name” field.

Step 3 − Now we have our package.json file set up, we will further install Express. To install Express and add it to our package.json file, use the following command −

npm install --save express

To confirm that Express has installed correctly, run the following code.

ls node_modules #(dir node_modules for windows)

Tip − The --save flag can be replaced by the -S flag. This flag ensures that Express is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project we can just run the command npm install and it will find the dependencies in this file and install them for us.

This is all we need to start development using the Express framework. To make our development process a lot easier, we will install a tool from npm, nodemon. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command −

npm install -g nodemon

You can now start working on Express.

ExpressJS - Hello World

We have set up the development, now it is time to start developing our first app using Express. Create a new file called index.js and type the following in it.

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

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

app.listen(3000);

Save the file, go to your terminal and type the following.

nodemon index.js

This will start the server. To test this app, open your browser and go to http://localhost:3000 and a message will be displayed as in the following screenshot.

Hello world




How the App Works?

The first line imports Express in our file, we have access to it through the variable Express. We use it to create an application and assign it to var app.

app.get(route, callback)

This function tells what to do when a get request at the given route is called. The callback function has 2 parameters, request(req) and response(res). The request object(req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc. Similarly, the response object represents the HTTP response that the Express app sends when it receives an HTTP request.

res.send()

This function takes an object as input and it sends this to the requesting client. Here we are sending the string "Hello World!".

app.listen(port, [host], [backlog], [callback]])

This function binds and listens for connections on the specified host and port. Port is the only required parameter here.

S.No.Argument & Description
1

port

A port number on which the server should accept incoming requests.

2

host

Name of the domain. You need to set it when you deploy your apps to the cloud.

3

backlog

The maximum number of queued pending connections. The default is 511.

4

callback

An asynchronous function that is called when the server starts listening for requests.

ExpressJS - Routing

Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes.

The following function is used to define routes in an Express application −

app.method(path, handler)

This METHOD can be applied to any one of the HTTP verbs – get, set, put, delete. An alternate method also exists, which executes independent of the request type.

Path is the route at which the request will run.

Handler is a callback function that executes when a matching request type is found on the relevant route. For example,

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

app.get('/hello', function(req, res){
   res.send("Hello World!");
});

app.listen(3000);

If we run our application and go to localhost:3000/hello, the server receives a get request at route "/hello", our Express app executes the callback function attached to this route and sends "Hello World!" as the response.

Hello

We can also have multiple different methods at the same route. For example,

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

app.get('/hello', function(req, res){
   res.send("Hello World!");
});

app.post('/hello', function(req, res){
   res.send("You just called the post method at '/hello'!\n");
});

app.listen(3000);

To test this request, open up your terminal and use cURL to execute the following request −

curl -X POST "http://localhost:3000/hello"

Curl request

A special method, all, is provided by Express to handle all types of http methods at a particular route using the same function. To use this method, try the following.

app.all('/test', function(req, res){
   res.send("HTTP method doesn't have any effect on this route!");
});

This method is generally used for defining middleware, which we'll discuss in the middleware chapter.

Routers

Defining routes like above is very tedious to maintain. To separate the routes from our main index.js file, we will use Express.Router. Create a new file called things.js and type the following in it.

var express = require('express');
var router = express.Router();

router.get('/', function(req, res){
   res.send('GET route on things.');
});
router.post('/', function(req, res){
   res.send('POST route on things.');
});

//export this router to use in our index.js
module.exports = router;

Now to use this router in our index.js, type in the following before the app.listen function call.

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

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

//both index.js and things.js should be in same directory
app.use('/things', things);

app.listen(3000);

The app.use function call on route '/things' attaches the things router with this route. Now whatever requests our app gets at the '/things', will be handled by our things.js router. The '/' route in things.js is actually a subroute of '/things'. Visit localhost:3000/things/ and you will see the following output.

Router Things

Routers are very helpful in separating concerns and keep relevant portions of our code together. They help in building maintainable code. You should define your routes relating to an entity in a single file and include it using the above method in your index.js file.

ExpressJS - HTTP Methods

The HTTP method is supplied in the request and specifies the operation that the client has requested. The following table lists the most used HTTP methods −

S.No.Method & Description
1

GET

The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect.

2

POST

The POST method requests that the server accept the data enclosed in the request as a new object/entity of the resource identified by the URI.

3

PUT

The PUT method requests that the server accept the data enclosed in the request as a modification to existing object identified by the URI. If it does not exist then the PUT method should create one.

4

DELETE

The DELETE method requests that the server delete the specified resource.

These are the most common HTTP methods. To learn more about the methods, visit http://www.tutorialspoint.com/http/http_methods.htm.

ExpressJS - URL Building

We can now define routes, but those are static or fixed. To use the dynamic routes, we SHOULD provide different types of routes. Using dynamic routes allows us to pass parameters and process based on them.

Here is an example of a dynamic route −

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

app.get('/:id', function(req, res){
res.send('The id you specified is ' + req.params.id);
});
app.listen(3000);

To test this go to http://localhost:3000/123. The following response will be displayed.

URL Building 1

You can replace '123' in the URL with anything else and the change will reflect in the response. A more complex example of the above is −

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

app.get('/things/:name/:id', function(req, res) {
   res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
app.listen(3000);

To test the above code, go to http://localhost:3000/things/tutorialspoint/12345.

URL Building 2

You can use the req.params object to access all the parameters you pass in the url. Note that the above 2 are different paths. They will never overlap. Also if you want to execute code when you get '/things' then you need to define it separately.

Pattern Matched Routes

You can also use regex to restrict URL parameter matching. Let us assume you need the id to be a 5-digit long number. You can use the following route definition −

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

app.get('/things/:id([0-9]{5})', function(req, res){
   res.send('id: ' + req.params.id);
});

app.listen(3000);

Note that this will only match the requests that have a 5-digit long id. You can use more complex regexes to match/validate your routes. If none of your routes match the request, you'll get a "Cannot GET <your-request-route>" message as response. This message be replaced by a 404 not found page using this simple route −

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

//Other routes here
app.get('*', function(req, res){
   res.send('Sorry, this is an invalid URL.');
});
app.listen(3000);

Important − This should be placed after all your routes, as Express matches routes from start to end of the index.js file, including the external routers you required.

For example, if we define the same routes as above, on requesting with a valid URL, the following output is displayed. −

Correct regex

While for an incorrect URL request, the following output is displayed.

Invalid regex(404)

ExpressJS - Middleware

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers, etc.

Here is a simple example of a middleware function in action −

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

//Simple request time logger
app.use(function(req, res, next){
   console.log("A new request received at " + Date.now());
   
   //This function call is very important. It tells that more processing is
   //required for the current request and is in the next middleware
   function route handler.
   next();
});

app.listen(3000);

The above middleware is called for every request on the server. So after every request, we will get the following message in the console −

A new request received at 1467267512545

To restrict it to a specific route (and all its subroutes), provide that route as the first argument of app.use(). For Example,

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

//Middleware function to log request protocol
app.use('/things', function(req, res, next){
   console.log("A request for things received at " + Date.now());
   next();
});

// Route handler that sends the response
app.get('/things', function(req, res){
   res.send('Things');
});

app.listen(3000);

Now whenever you request any subroute of '/things', only then it will log the time.

Order of Middleware Calls

One of the most important things about middleware in Express is the order in which they are written/included in your file; the order in which they are executed, given that the route matches also needs to be considered.

For example, in the following code snippet, the first function executes first, then the route handler and then the end function. This example summarizes how to use middleware before and after route handler; also how a route handler can be used as a middleware itself.

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

//First middleware before response is sent
app.use(function(req, res, next){
   console.log("Start");
   next();
});

//Route handler
app.get('/', function(req, res, next){
   res.send("Middle");
   next();
});

app.use('/', function(req, res){
   console.log('End');
});

app.listen(3000);

When we visit '/' after running this code, we receive the response as Middle and on our console −

Start
End

The following diagram summarizes what we have learnt about middleware −

Middleware

Now that we have covered how to create our own middleware, let us discuss some of the most commonly used community created middleware.

Third Party Middleware

A list of Third party middleware for Express is available here. Following are some of the most commonly used middleware; we will also learn how to use/mount these −

body-parser

This is used to parse the body of requests which have payloads attached to them. To mount body parser, we need to install it using npm install --save body-parser and to mount it, include the following lines in your index.js −

var bodyParser = require('body-parser');

//To parse URL encoded data
app.use(bodyParser.urlencoded({ extended: false }))

//To parse json data
app.use(bodyParser.json())

To view all available options for body-parser, visit its github page.

cookie-parser

It parses Cookie header and populate req.cookies with an object keyed by cookie names. To mount cookie parser, we need to install it using npm install --save cookie-parser and to mount it, include the following lines in your index.js −

var cookieParser = require('cookie-parser');
app.use(cookieParser())

express-session

It creates a session middleware with the given options. We will discuss its usage in the Sessions section.

We have many other third party middleware in ExpressJS. However, we have discussed only a few important ones here.

ExpressJS - Templating

Pug is a templating engine for Express. Templating engines are used to remove the cluttering of our server code with HTML, concatenating strings wildly to existing HTML templates. Pug is a very powerful templating engine which has a variety of features including filters, includes, inheritance, interpolation, etc. There is a lot of ground to cover on this.

To use Pug with Express, we need to install it,

npm install --save pug

Now that Pug is installed, set it as the templating engine for your app. You don't need to 'require' it. Add the following code to your index.js file.

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

Now create a new directory called views. Inside that create a file called first_view.pug, and enter the following data in it.

doctype html
html
   head
      title = "Hello Pug"
   body
      p.greetings#people Hello World!

To run this page, add the following route to your app −

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

You will get the output as − Hello World! Pug converts this very simple looking markup to html. We don’t need to keep track of closing our tags, no need to use class and id keywords, rather use '.' and '#' to define them. The above code first gets converted to −

<!DOCTYPE html>
<html>
   <head>
      <title>Hello Pug</title>
   </head>
   
   <body>
      <p class = "greetings" id = "people">Hello World!</p>
   </body>
</html>

Pug is capable of doing much more than simplifying HTML markup.

Important Features of Pug

Let us now explore a few important features of Pug.

Simple Tags

Tags are nested according to their indentation. Like in the above example, <title> was indented within the <head> tag, so it was inside it. But the <body> tag was on the same indentation, so it was a sibling of the <head> tag.

We don’t need to close tags, as soon as Pug encounters the next tag on same or outer indentation level, it closes the tag for us.

To put text inside of a tag, we have 3 methods −

  • Space seperated

h1 Welcome to Pug
  • Piped text

div
| To insert multiline text,
| You can use the pipe operator.
  • Block of text

div.
But that gets tedious if you have a lot of text.
You can use "." at the end of tag to denote block of text.
To put tags inside this block, simply enter tag in a new line and
indent it accordingly.

Comments

Pug uses the same syntax as JavaScript(//) for creating comments. These comments are converted to the html comments(<!--comment-->). For example,

//This is a Pug comment

This comment gets converted to the following.

<!--This is a Pug comment-->

Attributes

To define attributes, we use a comma separated list of attributes, in parenthesis. Class and ID attributes have special representations. The following line of code covers defining attributes, classes and id for a given html tag.

div.container.column.main#division(width = "100", height = "100")

This line of code, gets converted to the following. −

<div class = "container column main" id = "division" width = "100" height = "100"></div>

Passing Values to Templates

When we render a Pug template, we can actually pass it a value from our route handler, which we can then use in our template. Create a new route handler with the following.

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

app.get('/dynamic_view', function(req, res){
   res.render('dynamic', {
      name: "TutorialsPoint", 
      url:"http://www.tutorialspoint.com"
   });
});

app.listen(3000);

And create a new view file in views directory, called dynamic.pug, with the following code −

html
head
title=name
body
h1=name
a(href = url) URL

Open localhost:3000/dynamic_view in your browser; You should get the following output −

Variables in template

We can also use these passed variables within text. To insert passed variables in between text of a tag, we use #{variableName} syntax. For example, in the above example, if we wanted to put Greetings from TutorialsPoint, then we could have done the following.

html
head
title = name
body
h1 Greetings from #{name}
a(href = url) URL

This method of using values is called interpolation. The above code will display the following output. −

Templating Inter

Conditionals

We can use conditional statements and looping constructs as well.

Consider the following −

If a User is logged in, the page should display "Hi, User" and if not, then the "Login/Sign Up" link. To achieve this, we can define a simple template like −

html
head
title Simple template
body
if(user)
h1 Hi, #{user.name}
else
a(href = "/sign_up") Sign Up

When we render this using our routes, we can pass an object as in the following program −

res.render('/dynamic',{
user: {name: "Ayush", age: "20"}
});

You will receive a message − Hi, Ayush. But if we don’t pass any object or pass one with no user key, then we will get a signup link.

Buy me a coffee

Back to top