bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Node.js/Building Applications
Node.js•Building Applications

Node.js Express.js

Concept visual

Node.js Express.js

push / pop from the top({[← top

What is Express.js? Express.js (or simply Express) is the most popular Node.js web application framework, designed for building web applications and APIs. It's often called the de facto standard server framework for Node.js.

Key Characteristics:

Minimal and flexible

Unopinionated (you decide how to structure your app)

Lightweight and fast

Extensible through middleware

Huge ecosystem of plugins and extensions

Why Choose Express.js? Express provides a thin layer of fundamental web application features without obscuring Node.js features.

It offers:

A robust routing system

HTTP helpers (redirection, caching, etc.) Support for middleware to respond to HTTP requests

A templating engine for dynamic HTML rendering

Error handling middleware

Getting Started with Express

Express can be added to any Node.js project. Here's how to get started with a new Express application.

Prerequisites

Before you begin, make sure you have: Node.js installed (v14.0.0 or later recommended) npm (comes with Node.js) or yarn A code editor (VS Code, WebStorm, etc.)

Installing Express

To use Express in your Node.js application, you first need to install it: npm install express To install Express and save it in your package.json dependencies: npm install express --save

Hello World Example

Let's create a simple "Hello World" application with Express. This example demonstrates the basic structure of an Express application.

Key Components:

Importing the Express module

Creating an Express application instance

Defining routes

Starting the server const express = require('express');
const app = express();
const port = 8080;

// Define a route for GET requests to the root URL

app.get('/', (req, res) => {
res.send('Hello World from Express!');
});
// Start the server app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});

Save this code in a file named app.js and run it with Node.js: node app.js Then, open your browser and navigate to http://localhost:8080 to see the "Hello World" message.

Basic Routing

Routing refers to how an application responds to client requests to specific endpoints (URIs) using different HTTP methods (GET, POST, PUT, DELETE, etc.).

Express provides simple methods to define routes that correspond to HTTP methods: app.get() - Handle GET requests app.post() - Handle POST requests app.put() - Handle PUT requests app.delete()

- Handle DELETE requests app.all()
- Handle all HTTP methods const express = require('express');
const app = express();
const port = 8080;
// Respond to GET request on the root route app.get('/', (req, res) => {
res.send('GET request to the homepage');
});
// Respond to POST request on the root route app.post('/', (req, res) => {
res.send('POST request to the homepage');
});
// Respond to GET request on the /about route app.get('/about', (req, res) => {
res.send('About page');
});
// Catch all other routes app.all('*', (req, res) => {
res.status(404).send('404 - Page not found');
});
// Start the server app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});

Route Parameters

Route parameters are named URL segments that capture values at specific positions in the URL. They are specified in the path with a colon

prefix.

Example:

Formula

/users/:userId/books/:bookId

In this example, userId and bookId are route parameters that can be accessed via req.params.

const express = require('express');
const app = express();
const port = 8080;

Formula

// Route with parameters app.get('/users/:userId/books/:bookId', (req, res) => {

// Access parameters using req.params res.send(User ID: ${req.params.userId}, Book ID: ${req.params.bookId});

});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});

Query Parameters

Formula

Query parameters are key - value pairs that appear after the

? in a URL. They are automatically parsed by Express and available in req.query.

Example URL:

Formula

http://example.com/search?q = express&page = 2
In this URL, q = express and page = 2 are query parameters that can be accessed as req.query.q and req.query.page.
const express = require('express');
const app = express();
const port = 8080;
// Route handling query parameters app.get('/search', (req, res) => {
// Access query parameters using req.query const { q, category } = req.query;
res.send(`Search query: ${q}, Category: ${category || 'none'}`);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});

Access this route with a URL like:

Formula

http://localhost:8080/search?q = express&category = framework

Middleware in Express

Middleware functions are the backbone of Express applications.

Previous

Node.js Frameworks

Next

Node.js Middleware