Thursday, May 7, 2020

Node.js Express Introduction to express framework

Node.js Express Framework Tutorial


Introduction to express framework


  • Express Overview
  • Features of Express
  • Installing Express
  • "Hello World" Application
  • Express Application Generator
  • Basic Routing

Express Overview


Express is a minimal open-source and flexible Node.js based web application framework designed to create features rich websites, web apps, & API’s much easier.

It provides a thin wrapper of all general web application features around Node.js, without compromising any of the Node.js capability. Express facilitates the quick development single page, multi-page, and hybrid Node.js web applications. 

Features of Express


The key features of express.js are

  • Express applications are fast, robust, and asynchronous.
  • Express allows us to set up middlewares to respond to HTTP Requests.
  • Express defines a routing table that is used to perform different actions based on the HTTP Method(GET, POST, PUT, DELETE, etc.) and URL.
  • Express supports multiple templating engines to simplify generating HTML and enables us to dynamically render HTML pages on the basis of arguments provided to the templates.

Installing Express


To install the Express and save it in the dependencies list run the following command.

npm install express --save

To install Express temporarily and not add it to the dependencies list, execute the following command

npm install express --no-save

express nodejs
Express installation


"Hello World" Application


const express = require('express');
const app = express();
const port = 3000;
app.get('/', function(request, response){ response.send('Hello World!')});
app.listen(port, function(){console.log(`Hello World, server is listening at http://localhost:${port}`)});

This code starts a server and listens on port 3000. The app provides a response with “Hello World!” for requests to the root URL (/) or path. For other paths, the server will respond with 404 Not Found response.

Express Application Generator

We can use the application generator tool called express-generator to rapidly generate an application skeleton. The application generator can be executed with the npx command.

$ npx express-generator
The command options can be seen with -help command

C:\Users\user>express -help

  warning: option `--ejs' has been renamed to `--view=ejs'


  Usage: express [options] [dir]

  Options:

        --version        output the version number
    -e, --ejs            add ejs engine support
        --pug            add pug engine support
        --hbs            add handlebars engine support
    -H, --hogan          add hogan.js engine support
    -v, --view <engine>  add view <engine> support (dust|ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
        --no-view        use static html instead of view engine
    -c, --css <engine>   add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
        --git            add .gitignore
    -f, --force          force on non-empty directory
    -h, --help           output usage information


For example, To create an Express app with name testApp in the current working directory the view engine will be set to Pug;

C:\Users\user\Desktop>express --view=pug testApp

   create : testApp\
   create : testApp\public\
   create : testApp\public\javascripts\
   create : testApp\public\images\
   create : testApp\public\stylesheets\
   create : testApp\public\stylesheets\style.css
   create : testApp\routes\
   create : testApp\routes\index.js
   create : testApp\routes\users.js
   create : testApp\views\
   create : testApp\views\error.pug
   create : testApp\views\index.pug
   create : testApp\views\layout.pug
   create : testApp\app.js
   create : testApp\package.json
   create : testApp\bin\
   create : testApp\bin\www

   change directory:
     > cd testApp

   install dependencies:
     > npm install

   run the app:
     > SET DEBUG=testapp:* & npm start

Further dependencies can be added as,

C:\Users\user\Desktop>cd testApp

C:\Users\user\Desktop\testApp>npm install

The testApp structure will appear like,


The package.json file defines the application dependencies and other information. It also used to define a startup script that will call the application entry point, the JavaScript file /bin/www. The app routes are placed in a different module in the routes/ directory. The templates are kept in the /views directory.

Execute the following command run to the app(MacOS or Linux) 

DEBUG=testApp:* npm start

on Windows, run

set DEBUG=testApp:* & npm start

The server will serve at http://localhost:3000/

The following page will be displayed by default,


View Engine


The Application Generator makes us to easily configure a number of popular views/template engines, such as EJS, Hbs, Pug (Jade), Twig, and Vash. Jade is chosen by default if no option is specified.


CSS Engine


The Application Generator enables us to configure the project with commonly CSS stylesheet engines such as LESS, SASS, Compass, Stylus.


Basic Routing


The response of an application to a particular client’s request is determined by the routing that is an endpoint and a specified HTTP request method (POST, GET, PUT, etc.)

app.method(path, handler)

Here app is an instance of express. The method is an HTTP request method(POST, GET, etc.) and the path represents a path on the server. The handler is a function that will be executed when the route is matched.

app.get('/', function (req, res) {
  res.send('Got a GET request')
})
app.post('/', function (req, res) {
  res.send('Got a POST request')
})
app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})
app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at user')
})