Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It facilitates the rapid development of Node-based web applications by providing a simple and straightforward API. This chapter will cover the basics to advanced usage of Express.js, providing detailed explanations and examples to ensure a comprehensive understanding.
Express.js is a web application framework for Node.js, designed for building single-page, multi-page, and hybrid web applications. It’s the backend part of the popular MEAN (MongoDB, Express, Angular, Node) stack.
To install Express.js, you need to have Node.js and npm (Node Package Manager) installed. You can then create a new project and install Express:
mkdir express-app
cd express-app
npm init -y
npm install express
Create a file named app.js
and add the following code to set up a basic Express server:
File: app.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
const express = require('express');
: Imports the Express module.const app = express();
: Creates an Express application.app.get('/', callback)
: Defines a route handler for the root URL (/
).res.send('Hello, Express!')
: Sends a response back to the client.app.listen(port, callback)
: Starts the server and listens on the specified port.Running the script with node app.js
starts the server. Visit http://localhost:3000
in your browser to see the “Hello, Express!” message.
Routing refers to how an application’s endpoints (URIs) respond to client requests. Express provides a robust routing system that makes it easy to define routes.
File: app.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
app.get('/contact', (req, res) => {
res.send('Contact Page');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
app.get('/about', callback)
: Defines a route handler for /about
.app.get('/contact', callback)
: Defines a route handler for /contact
.http://localhost:3000
displays “Hello, Express!”.http://localhost:3000/about
displays “About Page”.http://localhost:3000/contact
displays “Contact Page”.Route parameters are named URL segments used to capture values specified at their position in the URL.
File: app.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/user/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
app.get('/user/:id', callback)
: Defines a route with a parameter id
.req.params.id
: Accesses the id
parameter from the URL.Visiting http://localhost:3000/user/123
displays “User ID: 123”.
Query parameters are used to filter data. They are appended to the URL after a ?
symbol.
File: app.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/search', (req, res) => {
res.send(`Search Query: ${req.query.q}`);
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
app.get('/search', callback)
: Defines a route for search queries.req.query.q
: Accesses the q
query parameter from the URL.Visiting http://localhost:3000/search?q=nodejs
displays “Search Query: nodejs”.
Middleware functions are functions that have access to the request object (req
), the response object (res
), and the next middleware function in the application’s request-response cycle. Middleware can perform the following tasks:
File: app.js
const express = require('express');
const app = express();
const port = 3000;
// Middleware function to log request details
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Pass control to the next middleware function
});
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
app.use(callback)
: Registers a middleware function that logs the request method and URL.next()
: Passes control to the next middleware function.Running the script logs the request details to the console for every request.
Express has several built-in middleware functions, including express.static
to serve static files and express.json
to parse JSON bodies.
File: app.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
// Middleware to serve static files
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
express.static(path)
: Serves static files from the specified directory.Creating a directory named public
and placing a file named index.html
in it will serve that file when visiting http://localhost:3000
.
Express can handle form submissions and file uploads using middleware such as body-parser
and multer
.
File: app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
// Middleware to parse URL-encoded bodies
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/form', (req, res) => {
res.send(`
`);
});
app.post('/submit', (req, res) => {
res.send(`Form submitted! Name: ${req.body.name}`);
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
bodyParser.urlencoded()
: Middleware to parse URL-encoded bodies.req.body.name
: Accesses the name
field from the form submission.Visiting http://localhost:3000/form
displays a form. Submitting the form displays the submitted name.
File: app.js
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const port = 3000;
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`);
}
});
const upload = multer({ storage: storage });
app.get('/upload', (req, res) => {
res.send(`
`);
});
app.post('/upload', upload.single('file'), (req, res) => {
res.send(`File uploaded! ${req.file.filename}`);
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
multer.diskStorage()
: Configures the storage engine for Multer.upload.single('file')
: Middleware to handle single file uploads.req.file.filename
: Accesses the uploaded file’s name.Visiting http://localhost:3000/upload
displays an upload form. Uploading a file displays the uploaded file’s name.
Templating engines allow you to generate HTML dynamically based on your data. Express supports various templating engines like Pug, EJS, and Handlebars.
File: app.js
const express = require('express');
const app = express();
const port = 3000;
// Set Pug as the templating engine
app.set('view engine', 'pug');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('index', { title: 'Express', message: 'Hello, Pug!' });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
views/index.pug
doctype html
html
head
title= title
body
h1= message
app.set('view engine', 'pug')
: Sets Pug as the templating engine.app.set('views', './views')
: Sets the directory for the views.res.render(view, data)
: Renders the specified view with the provided data.Visiting http://localhost:3000
displays “Hello, Pug!”.
Error handling middleware is used to catch and process errors that occur during request handling.
File: app.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
// Middleware to handle 404 errors
app.use((req, res, next) => {
res.status(404).send('Page not found');
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
app.use((req, res, next))
: Middleware to handle 404 errors.app.use((err, req, res, next))
: Error handling middleware to catch and process errors.Visiting a non-existent route displays “Page not found”. Errors are logged and a 500 error is sent to the client.
Express is widely used for building RESTful APIs. Here, we’ll create a simple API to manage a list of users.
File: app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
let users = [];
// Get all users
app.get('/users', (req, res) => {
res.json(users);
});
// Create a new user
app.post('/users', (req, res) => {
const user = req.body;
users.push(user);
res.status(201).json(user);
});
// Get a user by ID
app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) {
return res.status(404).send('User not found');
}
res.json(user);
});
// Update a user by ID
app.put('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) {
return res.status(404).send('User not found');
}
Object.assign(user, req.body);
res.json(user);
});
// Delete a user by ID
app.delete('/users/:id', (req, res) => {
const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
if (userIndex === -1) {
return res.status(404).send('User not found');
}
users.splice(userIndex, 1);
res.status(204).send();
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
app.use(bodyParser.json())
: Middleware to parse JSON bodies.app.get('/users', callback)
: Fetches all users.app.post('/users', callback)
: Creates a new user.app.get('/users/:id', callback)
: Fetches a user by ID.app.put('/users/:id', callback)
: Updates a user by ID.app.delete('/users/:id', callback)
: Deletes a user by IDThis script provides a full CRUD API for managing users. You can interact with this API using tools like Postman or CURL.
Express.js is a powerful and flexible framework for building web applications and APIs with Node.js. It provides a robust set of features and middleware, making it easy to develop complex applications quickly. This chapter has covered the basics to advanced usage of Express.js, from setting up a server, routing, and middleware, to handling forms and file uploads, using templating engines, error handling, and building RESTful APIs. With the examples and explanations provided, you should have a solid foundation to start developing your own Express.js applications.Happy coding !❤️