Node JS introduction to Express.js


Express.js is a popular web application framework for Node.js that simplifies the process of building robust and scalable web applications and APIs. It provides a set of features and tools that streamline the development of server-side applications, making it easier to handle routing, middleware, and other common web development tasks.

Here’s an introduction to Express.js:

1. What is Express.js?

Express.js is a minimalist and flexible Node.js web application framework that offers a simple and powerful way to build web servers and APIs. It builds on top of Node.js's HTTP module, providing additional functionality and abstractions to make server-side development easier.

2. Key Features of Express.js

  • Routing: Easily define routes for handling different HTTP requests (GET, POST, PUT, DELETE, etc.).
  • Middleware: Use middleware functions to process requests, perform operations, and handle responses.
  • Flexibility: Lightweight and unopinionated, allowing you to structure your application as you prefer.
  • Templating Engines: Integrate with various templating engines like EJS, Pug, and Handlebars for rendering dynamic views.
  • Error Handling: Simplify error handling with built-in support for middleware-based error handling.

3. Setting Up Express.js

3.1 Installation

To use Express.js, you first need to install it via npm (Node Package Manager). Create a new project directory and run the following commands:

mkdir my-express-app cd my-express-app npm init -y npm install express

3.2 Basic Application

Create a file named app.js (or server.js) in your project directory. Here’s a simple Express.js application:

const express = require('express'); const app = express(); const port = 3000; // Define a route app.get('/', (req, res) => { res.send('Hello, world!'); }); // Start the server app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); });
  • express(): Creates an instance of an Express application.
  • app.get(path, callback): Defines a route that responds to HTTP GET requests.
  • app.listen(port, callback): Starts the server on the specified port and runs the callback function once the server is running.

4. Routing

4.1 Route Definition

Express.js allows you to define routes for handling different HTTP methods and paths. Here’s an example with multiple routes:

// Define a route for GET requests to '/about' app.get('/about', (req, res) => { res.send('About page'); }); // Define a route for POST requests to '/submit' app.post('/submit', (req, res) => { res.send('Form submitted'); });

4.2 Route Parameters

You can use route parameters to capture values from the URL.

// Define a route with a route parameter app.get('/users/:userId', (req, res) => { const userId = req.params.userId; res.send(`User ID: ${userId}`); });

5. Middleware

Middleware functions are used to handle requests and responses. They can modify request objects, terminate requests, or call the next middleware function in the stack.

5.1 Using Built-in Middleware

Express.js provides built-in middleware for handling tasks such as serving static files and parsing request bodies.

// Serve static files from the 'public' directory app.use(express.static('public')); // Parse JSON request bodies app.use(express.json());

5.2 Custom Middleware

You can also create custom middleware functions.

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

6. Error Handling

Express.js allows you to define error-handling middleware to catch and handle errors.

Example:

// Error-handling middleware app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });
  • Error-handling middleware is defined with four arguments: err, req, res, and next.

7. Templating Engines

Express.js can integrate with templating engines to render dynamic HTML pages.

Example with EJS:

  1. Install EJS:

    npm install ejs
  2. Configure Express to use EJS:

    app.set('view engine', 'ejs'); app.set('views', './views'); // Set the views directory
  3. Create a view file index.ejs in the views directory:

    <!DOCTYPE html> <html> <head> <title>My App</title> </head> <body> <h1>Hello, <%= name %>!</h1> </body> </html>
  4. Render the view in a route:

    app.get('/', (req, res) => { res.render('index', { name: 'World' }); });

8. Summary

  • Express.js is a flexible and minimalist framework for building web applications and APIs in Node.js.
  • Routing: Define and manage routes for different HTTP methods and paths.
  • Middleware: Use built-in and custom middleware to handle requests and responses.
  • Error Handling: Implement error-handling middleware to manage errors.
  • Templating Engines: Integrate with templating engines like EJS for rendering dynamic views.