Express.js is a flexible and minimal web application framework for Node.js that provides robust features for building web and mobile applications. In this guide, we'll cover the basics of using Express.js, including installation, global objects, application properties, request and response handling, and body parsing.
Setting Up Express.js
Step 1: Installing Express
You can install Express using either npm or yarn. Here are the commands for both:
Using npm:
npm install express --save
Using yarn:
yarn add express
If you are working with TypeScript, you should also install the type definitions for Express:
yarn add -D @types/express
Step 2: Initializing an Express Application
To start using Express, you need to import the library and initialize it in your project:
const express = require("express"); // Importing the express library
const app = express(); // Initializing the express application
Global Objects in Express
JSON Middleware
Express provides built-in middleware for parsing JSON bodies from incoming requests.
Usage:
app.use(express.json([options]));
Options:
inflate
: Manage the deflated bodies (enabled or disabled).limit
: Controls the maximum request body size.reviver
: Directly passed toJSON.parse
as the second argument.type
: Determines the type of middleware that will parse.verify
: A function to verify the middleware parsing.
Raw Middleware
The express.raw
middleware parses incoming requests with raw payloads.
Usage:
app.use(express.raw([options]));
Options:
Similar to express.json
, with additional settings for handling raw data.
Router Middleware
The express.Router
middleware is used for creating modular, mountable route handlers.
Usage:
const router = express.Router([options]);
Options:
caseSensitive
: Enables case-sensitive routing.mergeParams
: If child and parent params conflict, the child takes precedence.strict
: Enables strict routing.
Static Middleware
The express.static
middleware serves static files from the specified root directory.
Usage:
app.use(express.static(root, [options]));
Options:
dotfiles
: Determines how dotfiles (e.g.,.gitignore
) are handled.etag
: Controls theetag
generation.extensions
: Fallback for file extensions.fallthrough
: Enables or disables theimmutable
directive in theCache-Control
response header.index
: Specifies the directory index file to serve.lastModified
: Sets theLast-Modified
header to the last modified date.setHeaders
: Function to set custom HTTP headers.
Text Middleware
The express.text
middleware parses text bodies.
Usage:
app.use(express.text([options]));
Options:
defaultCharset
: Sets the default charset for text content.inflate
: Manages deflated bodies.limit
: Controls the maximum request body size.type
: Determines the type of middleware that will parse.verify
: Function to verify the middleware parsing.
URL-Encoded Middleware
The express.urlencoded
middleware parses URL-encoded bodies.
Usage:
app.use(express.urlencoded([options]));
Options:
extended
: Allows choosing between parsing the URL-encoded data withquerystring
orqs
library.parameterLimit
: Controls the number of parameters.inflate
: Manages deflated bodies.limit
: Controls the maximum request body size.type
: Determines the type of middleware that will parse.verify
: Function to verify the middleware parsing.
Application Properties and Methods
Application Properties
app.locals
: Used for storing local variables that are available within the app.app.locals.title = "My Cheatsheet";
console.dir(app.locals.title); // Outputs: "My Cheatsheet"app.mountpath
: Retrieves the mount path of a sub-app.const admin = express();
admin.get('/', (req, res) => {
console.log(admin.mountpath); // Outputs the mount path
res.send('Admin Homepage');
});
app.use('/admin', admin);
Application Events
You can listen for specific events within your application:
mount
: Event triggered when a sub-app is mounted.admin.on('mount', (parent) => {
console.log('Admin Mounted');
});
HTTP Methods
Express supports various HTTP methods for routing:
app.get
: Handles GET requests.app.get('/', (req, res) => {
res.send('GET request to the homepage');
});app.post
: Handles POST requests.app.post('/', (req, res) => {
res.send('POST request to the homepage');
});app.put
: Handles PUT requests.app.put('/', (req, res) => {
res.send('PUT request to the homepage');
});app.delete
: Handles DELETE requests.app.delete('/', (req, res) => {
res.send('DELETE request to the homepage');
});app.all
: Handles all HTTP request methods.app.all('/secret', (req, res, next) => {
console.log('Accessing the secret section...');
next();
});app.param
: Adds callback triggers to route parameters.app.param('user', (req, res, next, id) => {
User.find(id, (err, user) => {
if (err) {
next(err);
} else if (user) {
req.user = user;
next();
} else {
next(new Error('Failed to load user'));
}
});
});app.use
: Adds middleware layers.app.use((req, res, next) => {
res.send('Hey There!');
});
Request and Response Handling
Request Methods
req.get
: Returns the specified HTTP request header.req.get('content-type'); // Returns the content-type header
req.accepts
: Checks if the specified content types are acceptable.req.accepts('html'); // Returns 'html' if it is acceptable
req.is
: Checks if the request is of a specified content type.req.is('json'); // Returns 'json' if the content type is json
req.range
: Parses the range header.const range = req.range(1000);
if (range.type === 'bytes') {
range.forEach((r) => {
// Your code
});
}
Request Properties
req.param
: Returns the specified parameter.req.param('name'); // Returns the 'name' parameter
req.body
: Contains the parsed body of the request.app.post('/', (req, res, next) => {
console.log(req.body);
res.json(req.body);
});req.cookies
: Contains the cookies sent by the request.console.dir(req.cookies.name); // Logs the 'name' cookie
req.query
: Contains the query string parameters.console.dir(req.query.q); // Logs the 'q' query parameter
req.route
: Contains the matched route information.console.log(req.route); // Outputs the matched route information
res.send('GET');req.signedCookies
: Contains the signed cookies sent by the request.console.dir(req.signedCookies.user); // Logs the 'user' signed cookie
Response Methods
res.redirect
: Redirects to a specified URL.res.redirect('https://google.com'); // Redirects to Google
res.send
: Sends a response of various types.res.send({message: 'Awesome Stuff'}); // Sends an object as a response
res.json
: Sends a JSON response.res.json({alert: 'awesomecheatsheets'}); // Sends a JSON response
res.sendFile
: Sends a file as an attachment.const file = req.params.name;
res.sendFile(file, options, (err) => {
if (err) {
next(err);
} else {
console.log('Sent:', file);
}
});res.render
: Renders a view template.res.render('index'); // Renders the 'index' template
Body Parsing Middleware
Express integrates body-parser middleware to parse incoming request bodies.
Usage:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
bodyParser.json()
: Parses JSON bodies.bodyParser.urlencoded({ extended: true })
: Parses URL-encoded bodieswith extended option.
By following this guide, you should have a solid foundation for building and managing web applications with Express.js.