Skip to main content

Express.js Overview

Express.js Overview.

Introduction

Express.js is a fast and minimalist web application framework for Node.js. It provides a simple and powerful way to build web applications and APIs. With its robust set of features and easy-to-use syntax, Express.js has become one of the most popular web development frameworks.

History

Express.js was created by TJ Holowaychuk and released in 2010. It was designed as a lightweight alternative to the more complex and feature-rich frameworks available at the time. Since its release, Express.js has gained a large and active community of developers, making it a go-to choice for building web applications in Node.js.

Features

  1. Routing: Express.js allows you to define routes for handling different HTTP requests. Here's an example of a basic route that responds with "Hello, World!" when a GET request is made to the root URL ("/"):
const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.send('Hello, World!');
});

app.listen(3000, () => {
console.log('Server started on port 3000');
});

When you run this code and visit http://localhost:3000 in your browser, you will see the message "Hello, World!".

  1. Middleware: Express.js uses middleware functions to handle requests and perform additional tasks. Middleware functions can be used for tasks such as logging, authentication, and error handling. Here's an example of a middleware function that logs the URL of every request:
const express = require('express');
const app = express();

app.use((req, res, next) => {
console.log(`Received request: ${req.url}`);
next();
});

app.get('/', (req, res) => {
res.send('Hello, World!');
});

app.listen(3000, () => {
console.log('Server started on port 3000');
});

When you run this code and make a request to any URL, the server will log the URL in the console.

  1. Template Engines: Express.js supports various template engines, such as EJS and Pug, for rendering dynamic HTML pages. Here's an example of how to use the EJS template engine to render a dynamic page:
const express = require('express');
const app = express();

app.set('view engine', 'ejs');

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

app.listen(3000, () => {
console.log('Server started on port 3000');
});

Create a file named index.ejs in a directory called views and add the following content:

<html>
<head>
<title>Hello, <%= name %></title>
</head>
<body>
<h1>Hello, <%= name %></h1>
</body>
</html>

When you run this code and visit http://localhost:3000, you will see a page that says "Hello, John".

  1. Static Files: Express.js allows you to serve static files, such as CSS and JavaScript files, directly from a directory. Here's an example of serving static files from a directory called public:
const express = require('express');
const app = express();

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

app.listen(3000, () => {
console.log('Server started on port 3000');
});

Place your static files (e.g., CSS file named styles.css) in the public directory. You can then reference the static file in your HTML like this:

<link rel="stylesheet" href="/styles.css">
  1. Error Handling: Express.js provides error handling middleware to handle errors that occur during request processing. Here's an example of error handling middleware that logs an error message and sends a custom error page:
const express = require('express');
const app = express();

app.get('/', (req, res, next) => {
const error = new Error('Something went wrong');
next(error);
});

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

app.listen(3000, () => {
console.log('Server started on port 3000');
});

When you visit http://localhost:3000, an error will be thrown and the error handling middleware will log the error and send a response with the message "Something broke!".

For more detailed information and examples, you can refer to the official Express.js documentation at expressjs.com.

Examples

  1. Basic Express.js Server:
const express = require('express');
const app = express();

app.get('/', (req, res) => {
res.send('Hello, World!');
});

app.listen(3000, () => {
console.log('Server started on port 3000');
});

This example creates a basic Express.js server that listens on port 3000 and responds with "Hello, World!" when a GET request is made to the root URL ("/").

  1. Using Middleware:
const express = require('express');
const app = express();

app.use((req, res, next) => {
console.log(`Received request: ${req.url}`);
next();
});

app.get('/', (req, res) => {
res.send('Hello, World!');
});

app.listen(3000, () => {
console.log('Server started on port 3000');
});

This example demonstrates the usage of middleware in Express.js. The middleware function logs the URL of every request before passing it to the next handler.

  1. Rendering Dynamic Pages:
const express = require('express');
const app = express();

app.set('view engine', 'ejs');

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

app.listen(3000, () => {
console.log('Server started on port 3000');
});

In this example, the EJS template engine is used to render a dynamic HTML page. The index.ejs template file receives a name variable and displays a personalized greeting.

  1. Serving Static Files:
const express = require('express');
const app = express();

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

app.listen(3000, () => {
console.log('Server started on port 3000');
});

This example shows how to serve static files (e.g., CSS, JavaScript) from the public directory. The static files can be referenced in HTML using their relative paths.

  1. Error Handling:
const express = require('express');
const app = express();

app.get('/', (req, res, next) => {
const error = new Error('Something went wrong');
next(error);
});

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

app.listen(3000, () => {
console.log('Server started on port 3000');
});

In this example, an error is intentionally thrown when visiting the root URL. The error handling middleware logs the error stack trace and sends a custom error response with the message "Something broke!".

These examples provide a glimpse into the power and flexibility of Express.js. You can explore more features and functionalities by referring to the official documentation and experimenting with different code snippets.