The Express + Node.js Handbook – Learn the Express JavaScript Framework for Beginners
Introduction
Express.js is a lightweight and flexible web application framework for Node.js that simplifies the process of building robust and feature-rich web servers. In this comprehensive guide, you'll learn the fundamentals of Express and how to harness its capabilities to create scalable and efficient applications.
What is Express?
Express is a web framework built on top of Node.js. It extends the functionality of Node.js, making it easier to create web servers and applications with minimal code. Express is:
- Open Source: Free to use and community-driven.
- Easy to Extend: Highly customizable with middleware.
- Performance-Oriented: Optimized for speed and scalability.
- Rich Ecosystem: Thousands of pre-built packages available on npm.
If you're just starting with Express, this guide will help you get up and running quickly.
Table of Contents
- How to Install Express
- First "Hello, World" Example
- Handling Requests and Responses
- Managing Cookies
- Routing in Express
- Using Templates in Express
- Middleware in Express
- Serving Static Assets
- Handling File Uploads
- Sessions and Authentication
- Input Validation and Sanitization
1. How to Install Express
To begin, ensure you have Node.js installed on your machine. Follow these steps to install Express:
- Initialize a Node.js Project:
npm init -y
- Install Express:
npm install express
You're now ready to build your first Express application.
2. First "Hello, World" Example
Create a file named index.js
and add the following code:
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello, World!'));
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Run your server with:
node index.js
Open your browser and navigate to http://localhost:3000
to see the "Hello, World!" message.
Key Points:
-
require('express')
: Imports the Express library. -
express()
: Initializes an Express application. -
app.get()
: Sets up a route to handle HTTP GET requests. -
res.send()
: Sends a response back to the client. -
app.listen()
: Starts the server and listens on port 3000.
3. Handling Requests and Responses
Express simplifies handling HTTP requests and responses. Here’s a deeper dive into its capabilities:
Request Object (req
):
The req
object provides information about the HTTP request. Common properties include:
-
req.params
: Route parameters. -
req.query
: Query strings. -
req.body
: Request body (requires middleware likebody-parser
).
Response Object (res
):
The res
object allows you to send data back to the client. Common methods include:
-
res.send()
: Sends a plain text or HTML response. -
res.json()
: Sends a JSON response. -
res.status()
: Sets the HTTP status code. -
res.redirect()
: Redirects the client to another URL.
Example:
app.get('/user/:id', (req, res) => {
res.json({ userId: req.params.id, query: req.query });
});
4. Managing Cookies
Cookies are small pieces of data stored on the client. Use the cookie-parser
middleware to handle cookies in Express.
Installation:
npm install cookie-parser
Example:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/set-cookie', (req, res) => {
res.cookie('name', 'ExpressUser', { httpOnly: true });
res.send('Cookie set');
});
app.get('/get-cookie', (req, res) => {
res.send(`Cookie value: ${req.cookies.name}`);
});
5. Routing in Express
Routing defines how an application responds to client requests. You can define routes for specific HTTP methods and paths.
Example:
app.get('/', (req, res) => res.send('GET request received'));
app.post('/', (req, res) => res.send('POST request received'));
app.put('/update', (req, res) => res.send('PUT request received'));
app.delete('/delete', (req, res) => res.send('DELETE request received'));
Named Parameters and Query Strings:
app.get('/user/:id', (req, res) => res.send(`User ID: ${req.params.id}`));
app.get('/search', (req, res) => res.send(`Search query: ${req.query.q}`));
6. Using Templates in Express
Express supports template engines like Pug, EJS, and Handlebars to generate dynamic HTML.
Setting up Pug:
npm install pug
app.set('view engine', 'pug');
app.get('/about', (req, res) => {
res.render('about', { title: 'About Us', message: 'Welcome to Express!' });
});
views/about.pug
:
html
head
title= title
body
h1= message
7. Middleware in Express
Middleware functions execute during the lifecycle of a request.
Example:
app.use((req, res, next) => {
console.log(`${req.method} request for '${req.url}'`);
next();
});
Common Middleware:
-
body-parser
: Parses JSON and URL-encoded data. -
cors
: Enables Cross-Origin Resource Sharing. -
morgan
: Logs HTTP requests.
8. Serving Static Assets
Use express.static
to serve static files (e.g., CSS, images).
app.use(express.static('public'));
Place static files (e.g., index.html
) in the public
directory. They’ll be accessible at http://localhost:3000/filename
.
9. Handling File Uploads
To handle file uploads, use the multer
middleware.
Installation:
npm install multer
Example:
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('file'), (req, res) => {
res.send(`File uploaded: ${req.file.originalname}`);
});
10. Sessions and Authentication
Sessions enable you to persist user data between requests. Use express-session
to manage sessions.
Installation:
npm install express-session
Example:
const session = require('express-session');
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true
}));
app.get('/login', (req, res) => {
req.session.user = 'ExpressUser';
res.send('Logged in');
});
app.get('/profile', (req, res) => {
if (req.session.user) {
res.send(`Welcome back, ${req.session.user}`);
} else {
res.send('Please log in.');
}
});
11. Input Validation and Sanitization
Use express-validator
to validate and sanitize user input.
Installation:
npm install express-validator
Example:
const { check, validationResult } = require('express-validator');
app.post('/form', [
check('email').isEmail().withMessage('Enter a valid email'),
check('age').isInt({ min: 1 }).withMessage('Age must be a positive number')
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
res.send('Form submitted successfully');
});
Conclusion
Express.js is a powerful tool for building web applications. With its rich ecosystem and intuitive API, it caters to beginners and experienced developers alike. Explore its features, experiment with middleware, and start building your own web projects today!
Top comments (0)