Introduction to Express
In this section, we’ll introduce Express, a fast and minimalist web framework for Node.js. Express simplifies the process of building robust and scalable web applications and APIs. We’ll cover the basics of setting up an Express server, routing, and understanding middleware.
Installing and Setting Up Express
To get started with Express, you need to install it using npm.
Create a new Project Directory:
bash mkdir express-app cd express-app
Initialize a Node.js Project:
bash npm init -y
Install Express:
bash npm install express
Create the Entry Point: Create a file named
app.js
:javascript // Importing the Express module const express = require('express'); // Creating an instance of an Express application const app = express(); // Defining the port number where the server will listen for requests const port = 3000; // Setting up a route for the root URL app.get('/', (req, res) => { res.send('Hello, World!'); // Sending a response back to the client }); // Starting the server and logging a message to the console app.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
Run Your Express Server:
bash node app.js
Open a browser and go to
http://localhost:3000/
to see your “Hello, World!” message.Note: You will need to restart the server manually whenever you make changes to your code. We will cover automatic server restarts in a later section.
Basic Express Server Setup
In the example above, we set up a basic Express server that responds with “Hello, World!” to requests at the root URL. Let’s break down the components:
- Importing Express: We require the
express
module. - Creating an Application Instance:
const app = express();
creates an instance of an Express application. - Defining a Route:
app.get('/', ...)
sets up a route to handle GET requests at the root URL (/
). - Starting the Server:
app.listen(port, ...)
starts the server and listens for incoming requests on the specified port.
Understanding Middleware
Middleware functions are the backbone of Express applications. They are functions that execute during the request-response cycle.
Example: Using middleware to log requests:
// Middleware function to log request details
app.use((req, res, next) => {
console.log(`${req.method} request for '${req.url}'`);
next(); // Passing control to the next middleware function
});
// Route to handle GET requests at the root URL
app.get('/', (req, res) => {
res.send('Hello, World!');
});
- Middleware Function: A function that takes three arguments:
req
,res
, andnext
. It processes the request, performs some action, and then callsnext()
to pass control to the next middleware function.
Routing Basics
Routing in Express involves defining endpoints (URLs) and handling HTTP requests for those endpoints.
Example: Setting up multiple routes:
// Route to handle GET requests at the root URL
app.get('/', (req, res) => {
res.send('Home Page');
});
// Route to handle GET requests at the '/about' URL
app.get('/about', (req, res) => {
res.send('About Page');
});
// Route to handle GET requests at the '/contact' URL
app.get('/contact', (req, res) => {
res.send('Contact Page');
});
- Defining Routes:
app.get('/about', ...)
defines a route for GET requests at the/about
URL. - Handling Requests: Each route specifies a callback function to handle the request and send a response.
Summary
In this section, we’ve introduced Express, set up a basic Express server, and explored middleware and routing. You’ve learned how to install and configure Express, create routes, and use middleware to enhance your application.
Lesson task
We will create a simple Express server that responds with a custom message. You will set up the server, define a route, and use middleware to log requests.
Goal
The goal is for you to demonstrate that you know the basics of Node.js and Express by setting up a simple server and understanding middleware and routing.
Brief
Create a new Express server that has the following end-points:
/
: Responds with a custom message./about
: Respond with a custom message./contact
: Respond with a custom message.
Add a middleware function to log the request details for each incoming request.
NOTE: Lesson tasks do not get submitted on Moodle and are not assessed by tutors. They are mainly there for you to practise what you have learned in the lesson.