ExpressJS - Lightweight Yet Powerful NodeJS Module - ByteScout
  • Home
  • /
  • Blog
  • /
  • ExpressJS – Lightweight Yet Powerful NodeJS Module

ExpressJS – Lightweight Yet Powerful NodeJS Module

Express is the Node.js web application framework. It provides users with a robust set of features for developing mobile and web applications. ExpressJs helps provide a more straightforward API to work with the front-end and back-end of any application. Moreover, it takes care of the low-level protocols and procedures for the developers. Moreover, this module is fast and asynchronous. The original author TJ Holowaychuk released ExpressJS in 2010 as free and open-source software under the MIT License. This module is the back-end component for the development stacks such as MERN, MEAN, and MEVN with database software such as MongoDB and JavaScript as front-end framework.

ExpressJS Features

ExpressJs is an essential web framework and a layer built on Node.js, which helps manage the servers and routers. Following are some of the essential features of EspressJS:

  • Web Applications: Developers can use Express to design web applications that can be single-page, multi-page, and hybrid.
  • Middlewares: Express allows setting up middlewares for responding to HTTP requests. These middlewares lie between an OS and the applications running on it. The middlewares prove helpful in data communication and management, leading to better API management.
  • Routing Table: Express enables defining a routing table to perform various operations based on HTTP methods an URL. These methods include app.get(), app.post(), app.all() to handle every HTTP method, app.use() to specify middleware, app.put() and many other useful functions.

ExpressJS Examples

1.     Basic App Example

Following is a basic application example Using ExpressJs:

var express = require('express'); 
var app = express(); 
app.get('/', function (req, res) { 
  res.send('This is a sample app!'); 
}); 
var server = app.listen(8000, function () { 
  var host = server.address().address; 
  var port = server.address().port; 
  console.log('Sample app listening at http://%s:%s', host, port);
});

This example represents the development environment for a web server software using Express and setting up the system to use Node.js and npm.

2.     HTTP GET Example

Following is an example to deal with HTTP GET requests using Express. Here, the program responds to the GET requests using the app.get() and listens to the port using the app.listen() at which the program is running. Following is a basic code for executing this operation:

const express = require('express');
const app = express();
app.get('/', (req,res)=>{
    res.send('Application has received the request')
})
app.listen(5000, ()=>{
    console.log('Application is listening at https://localhost:5000')
})

ExpressJS Frameworks

Express is beneficial for developing frameworks for Node.js as it provides ultra-fast I/O operations, Model View Controler (MVC) structure, easy routing using a robust API, and an asynchronous model. Following are some of the popular frameworks that use ExpressJS:

●      Feathers

It is a web framework that helps create real-time applications such as Air Traffic Control Systems, Command Control Systems, Network Multimedia Systems, and many others.

●      ItemsAPI

It is a framework that is built using Express and ElasticSearch. It helps search the back-end for mobile and web applications. It works best for e-commerce, booking applications, and SEO-friendly catalogs.

●      Poet

It is a lightweight markdown blog generating engine. This generator in Node.js renders templates, generates routing, performs instant pagination, tag, and category views.

●      Blueprint

It is a framework to build APIs and back-end services. It provides features like encapsulation logic to reusable components, composing one application from another, customization and configuration based on the execution environment, and many others.

  • Dinoloop

Dinoloop is a REST API application framework. It helps in building Node.js server-side applications powered by TyeScript with dependency injection. It uses ExpressJs to reuse similar design patterns of C# and Java.

Routing With ExpressJS

The developers can define routing using methods of Express app object, which corresponds to HTTP methods. These methods specify a callback function when the application receives any request to the specified route. If there are multiple callback functions, there is a need to provide next as an argument to the callback function. Following is an example of a basic route code using Express:

var express = require('express')
var app = express()
app.get('/', function (req, res) {
  res.send('hello world')
})

Moreover, the following are basic examples of routes to utilize the GET and POST methods in the application:

app.get('/', function (req, res) {
  res.send('GET request to the homepage')
})
app.post('/', function (req, res) {
  res.send('POST request to the homepage')
})

Middleware With ExpressJs

The Middleware functions possess access to the request object, the response object, and the next function. The next function helps execute the middleware succeeding the current middleware. These middleware functions can execute any code, change the request and response object, terminate the request-response cycle, and call the next middleware. Following is an example of adding a simple middleware in the application that prints a log message. Assuming the basic application example mentioned above, the following is a simple middleware code to add to the application:

Application

var express = require('express'); 
var app = express(); 
app.get('/', function (req, res) { 
  res.send('Hello!'); 
})
app.listen(4000)

Middleware

var sample_func = function (req, res, next) {
  console.log('LOGGED')
  next()
}

Moreover, the app.use() can load this middleware function. Following is an example of loading the above middleware function before routing to the root path:

var express = require('express')
var app = express()
var sample_func = function (req, res, next) {
  console.log('LOGGED')
  next()
}
app.use(sample_func)
app.get('/', function (req, res) {
  res.send('Hello!')
})
app.listen(4000)

Similarly, there can be numerous middleware functions to deal with the request time, validate cookies, and many others. Moreover, the developers can configure the middleware by exporting a function to accept options object and other parameters, which returns the implementation considering the input parameters. Following is the sample implementation of middleware.js:

module.exports = function (options) {
  return function (req, res, next) {
    // Middleware implementation on Options object
    next()
  }
}

Following is the updated usage of middleware functions:

var mw = require('./middleware.js')
app.use(mw({ option1: '1', option2: '2' }))

Furthermore, the developers can use middleware functions, including application-level middleware, built-in middleware, router-level middleware, error-handling middleware, and third-party middleware in their Express application.

Express API

The API for ExpressJS possesses numerous methods and properties for the request and response objects. Following are the two extensions of the Express API:

  • Global prototypes at express.request and express.response
  • App-specific prototypes at app.request and app.response

If the users manipulate and change the global prototypes, this will affect every loaded Express application in the process. However, the users can customize the changes to be application-specific only by manipulating the app-specific prototypes after the new application creation.

Overriding Methods

The users can override the existing method’s behavior. The users have to assign a custom function for it. Following is the simple example of changing the res.sendStatus, which sets the response status code and sends the registered status message in a text response body.

app.response.sendStatus = function (statusCode, type, message) {
  return this.contentType(type)
    .status(statusCode)
    .send(message)
}

This overriding method technique alters the original signature of the method. It manipulates the method to accept a status code, encoding type, and the message to deliver to the client. Following is the code to use the updated method with overriding:

res.sendStatus(404, 'application/json', '{"error":"resource not found"}')

Template Engines With Express

Template engines allow using static template files in the user application. These engines replace the template file variables with actual values at the runtime and transform the template into an HTML file to send to the client. Popular template engines using ExpressJs are Mustache, Pug, and EJS (Embedded JavaScript). After setting the view engine, there is no need to load the template engine module or specify the engine. ExpressJS loads the module internally using the following code:

app.set('view engine', 'pug')

The next step is to create a file index.pug the views directory using the following content:

html
  head
    title= title
  body
    h1= message

The users have to create a router for rendering the index.pug file.

app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello!' })
})

Similarly, the users can also manipulate other functions with ExpressJS to make useful mobile and web applications.

   

About the Author

ByteScout Team ByteScout Team of Writers ByteScout has a team of professional writers proficient in different technical topics. We select the best writers to cover interesting and trending topics for our readers. We love developers and we hope our articles help you learn about programming and programmers.  
prev
next