Skip to content

Express JS

Express.js is a minimalist and flexible Node.js framework that provides a robust set of features for developing web applications and APIs. It is widely used due to its simplicity and extensibility. Below is a detailed overview of the operational theory of Express.js.

Express.js Operational Theory

1. Middleware-Based Architecture

Express uses a middleware-based architectural pattern, where intermediate functions (middleware) process requests and responses. Each middleware can modify the request and response or end the request-response cycle. This allows for the modular addition of functionalities.

Middleware Structure

A middleware is a function that receives three parameters: req (request), res (response), and next (a function that passes control to the next middleware).

const myMiddleware = (req, res, next) => {
  console.log('Request received!');
  next(); // Calls the next middleware
};

2. Installation and Setup

To start a project with Express, you need to install the library and create an application instance.

npm install express
const express = require('express');
const app = express();

3. Routing

Express allows you to define routes for different application endpoints. Routes can respond to different HTTP methods, such as GET, POST, PUT, and DELETE.

Routing Example

app.get('/users', (req, res) => {
  res.send('List of users');
});

app.post('/users', (req, res) => {
  res.send('User created');
});

4. Request and Response Handling

Express simplifies working with request and response objects, allowing you to easily access request data (such as parameters, body, and headers) and send responses.

Accessing Request Parameters and Body

app.get('/users/:id', (req, res) => {
  const userId = req.params.id; // Accessing URL parameters
  res.send(`User with ID: ${userId}`);
});

// To handle the request body, it's necessary to use middleware like body-parser
app.use(express.json());
app.post('/users', (req, res) => {
  const newUser = req.body; // Accessing the request body
  res.send(`User created: ${JSON.stringify(newUser)}`);
});

5. Middleware

Middleware is essential in Express, allowing you to add functionalities like authentication, error handling, logging, among others.

Logging Middleware Example

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // Passes to the next middleware
});

6. Error Handling

Express allows you to define specific error-handling middleware. An error middleware must have four parameters: err, req, res, and next.

Error Handling Middleware Example

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});

7. Serving Static Files

Express can serve static files (like HTML, CSS, and JavaScript) using the express.static middleware.

Example of Serving Static Files

app.use(express.static('public'));

8. Database Connection

Express can connect to databases, such as MongoDB, MySQL, etc., using appropriate libraries and middleware to perform CRUD operations.

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true });

9. Real-Time Applications

Express can be used in conjunction with libraries like Socket.io to create real-time applications, allowing for bidirectional communication between the client and the server.

10. Deployment

An Express application can be deployed in different environments, such as dedicated servers, cloud services (like Heroku, AWS), or Docker containers, making it highly flexible.