Menu

Getting Started with Express 4 framework

By Aravindan Chandrasekaran | Open Web

Feb 27
express

In our previous blog post, we presented a basic Node.js client-server application. In this post, we’ll be extending the functionality of Node with the  Express js framework.

What is Express js?

Express is a fast, minimalist web framework of Node.js. You can think of Express as a layer built on the top of the Node.js that helps to manage a server side app and its routes. It provides a robust set of features to develop web and mobile applications.

Here are some of the core features of Express framework:

  • It can be used to design single-page, multi-page and hybrid web applications.
  • It allows to setup middlewares to respond to HTTP Requests.
  • It defines a routing table which is used to perform different actions based on HTTP method and URL.
  • It allows dynamically rendering of HTML Pages.
  • It supports a robust API with MVC like structure.

Installing Express 4 and creating an express application

Create a new directory and under that, use the npm init command to create a package.json file for our application.

$ npm init

This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:

entry point: (index.js)

Here index.js will be the default application file. We can leave it as app.js also but I prefer index.js as it is easier to identify it with the website entry point like in the case of index.html. Now install Express locally in our newly created app directory and save it in the dependencies list.

$ npm install express - - save

Express-init

First step in building our Express js app

I’ll start with the customary hello world program to explain the basic components in an Express application.

Our application is going to create a simple server module which will listen on port number 3000. In our example, if a request is made through the browser on this port number, then server application will send a ‘Hello’ World’ response to the client.

// Using express module
var express = require('express'); 
// Creating an app object of express module
var app = express(); 
// Creating a callback to send hello world response
app.get('/',function(req,res){
    res.send("hello world");
}); 
// Creating server instance to listen to port 3000
var server = app.listen(3000,function(){
    console.log("server listening to port http://localhost:3000/");
});

 

Most of the code is self explanatory but here is a quick summary

  • In line 2, we use the require function to include the express module.
  • Before we can start using the express module, we need to make an object of the express module. That’s what we do in line 5.
  • In line 8, we define a callback function for the route ‘/’. This function will be called whenever anybody browses to the root of our web application which is http://localhost:3000 . The callback function will be used to send the string ‘hello world’ to the web page.
  • Finally, in line 13, we initialize the Node server by listening to client requests on port number 3000.

And here is the output on the web browser.

Express-output

 

The next important thing to be taken care is Express application structuring and Routing , so we’ll create another application. This time, it will be slightly more complex but also more interesting.

Express Application structuring

Use the application generator tool, express-generator, to quickly create an application skeleton. The express-generator package installs the express command-line tool. Use the following command to do so (under a new app directory):

$ npm install express-generator -g

Now use the express command-line tool to create an Express application named basicApp in the current working directory:

$ express --view=jade basicApp

Then install the dependencies:

$ cd basicApp
$ npm install

On Linux, run the app with this command:

$ DEBUG=basicApp:* npm start

The generated app has the following directory structure:

Express-application-generator

All static content like images, css , html and js are placed in public  directory and dynamic contents are placed in views directory. By default Express provides jade templating engine (jade now renamed to pug) for dynamic content. We can modify the app.js file for developing our basic application.

Routing in Express application

Organizing the application structure and its routes are one of the first problems we will encounter while developing with Express. To help us with that,  version 4 added the Router class.

A basic app for creating routes with Router is already provided in this GitHub repo.

Here is the index.js file in the routes directory under the repo, which uses the router class to display home and api pages.

var express = require('express');
var router = express.Router();
// Get home page
router.get('/', function(req, res, next) {
   res.render('index', { title: 'Express' });
});
// Get API page
router.get('/api',function(req,res){
    res.send("api request received");
});
module.exports = router;

Line 4 & 8 define the home and the api routes respectively. Similarly, more routes can be added to the application for building complex more complex web apps.

Now that the routes are defined, we need to load them in the main app.js Express app (Line 9, 29).

 

var index = require('./routes/index');
app.use('/', index);

 

This app will then respond to “ / “ or “ /api ” requests.

Express-Routing-api

There is another set of routes defined under users.js file in the routes directory.

router.get('/user1', function(req, res, next) {
    res.send('respond with a user 1 resource');
});

This one is exported in Line 10 and 30 as ‘/pages’ in the main app.js file.

express-user-resource

We can also have parameter in our route and respond according to it, for example in our users.js we have another route that is defined as

// route with parameters (http://localhost:3000/pages/anyname)
router.get('/:name', function(req, res, next) {
    res.send('hello ' + req.params.name + '!');
});

express-username-route

Notice how easy it is to organize your routes with the Router class. Routers don’t know where they are used, they only know the routes they define. This greatly simplifies dependencies and also makes the code more maintainable.

Express Middleware

Express.js Middleware are a set of different types of functions that are invoked by the Express.js routing layer before the final request handler. As the name specified, Middleware appears in the middle between an initial request and final intended route.

Middleware is commonly used to perform tasks like body parsing for URL-encoded or JSON requests, cookie parsing for basic cookie handling, or even building JavaScript modules on the fly.

Refer official documentation for more info on middleware and its usage.

Summary

With this post, we have now inched ahead in our quest for building a Node.js web application. In the next post of this series, we’ll present how to implement AJAX calls under Node/Express.

Follow

About the Author

Aravind is a technology enthusiast. He is an expert in conceptualizing and developing niche apps around IoT and cloud computing and is aspiring to be a full stack developer.

>