ExpressJS – Web framework for Node.js
Introduction
Express.js is a fast, unopinionated, and minimalist web framework for Node.js that simplifies the process of building web applications and APIs. As one of the most popular backend frameworks, Express.js provides developers with a robust set of features to create scalable and efficient web applications with minimal effort.
This article covers everything you need to know about Express.js, including its features, installation, setup, middleware, routing, database integration, error handling, and advanced concepts.
What is Express.js?
Express.js is a web application framework for Node.js that provides a simple way to manage routes, handle requests and responses, and integrate with databases. It serves as the foundation for many popular web applications, including RESTful APIs and full-stack applications using frameworks like React, Angular, or Vue.js.
Key Features
- Minimalist Framework – Provides only the essential tools, allowing developers to build applications with flexibility.
- Middleware Support – Easily add functions for request handling, authentication, logging, etc.
- Routing System – Manage HTTP routes efficiently.
- Template Engines – Supports Pug, EJS, Handlebars, etc., for rendering dynamic views.
- RESTful API Support – Ideal for building APIs with JSON responses.
- Error Handling – Provides built-in and custom error-handling mechanisms.
- Integration with Databases – Works with MongoDB, MySQL, PostgreSQL, etc.
- Scalability – Suitable for both small applications and large-scale enterprise solutions.
Installing Express.js
To start using Express.js, ensure you have Node.js installed. Then, follow these steps:
Step 1: Initialize a Node.js Project
mkdir express-app && cd express-app
npm init -y
This creates a package.json
file for managing dependencies.
Step 2: Install Express.js
npm install express
Now, Express.js is ready to use in your project.
Creating a Basic Express.js Server
Create a file server.js
and add the following code:
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}`);
});
Running the Server
node server.js
Visit http://localhost:3000/
in your browser, and you should see “Hello, Express!”.
Routing in Express.js
Express.js provides a simple way to define routes for different HTTP methods.
Defining Routes
app.get('/about', (req, res) => {
res.send('About Page');
});
app.post('/submit', (req, res) => {
res.send('Form Submitted');
});
Route Parameters
app.get('/user/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
Accessing /user/123
will return “User ID: 123”.
Middleware in Express.js
Middleware functions process requests before reaching the final handler.
Built-in Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
Custom Middleware
app.use((req, res, next) => {
console.log(`Request URL: ${req.url}`);
next();
});
Handling Forms and JSON Data
Express.js allows processing form data and JSON using middleware.
Parsing JSON Data
app.use(express.json());
app.post('/data', (req, res) => {
res.json(req.body);
});
Handling Form Data
app.use(express.urlencoded({ extended: true }));
app.post('/submit', (req, res) => {
res.send(`Received: ${req.body.name}`);
});
Connecting Express.js to a Database
Express.js works with various databases. Below is an example of connecting it to MongoDB using Mongoose.
Install Mongoose
npm install mongoose
Connecting to MongoDB
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.log(err));
Error Handling in Express.js
Express provides a way to handle errors effectively.
Simple Error Handling
app.use((req, res, next) => {
res.status(404).send('Page Not Found');
});
Centralized Error Handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
Advanced Topics
1. Using Template Engines
Express.js supports template engines like Pug and EJS.
npm install ejs
app.set('view engine', 'ejs');
app.get('/dashboard', (req, res) => {
res.render('dashboard', { username: 'JohnDoe' });
});
2. Building a RESTful API
Express.js is commonly used for building RESTful APIs.
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
app.get('/api/users', (req, res) => {
res.json(users);
});
3. Authentication with JWT
npm install jsonwebtoken bcryptjs
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
app.post('/login', async (req, res) => {
const token = jwt.sign({ userId: 123 }, 'secretKey', { expiresIn: '1h' });
res.json({ token });
});
Conclusion
Express.js is a powerful yet simple framework for building web applications and APIs with Node.js. Its flexibility, ease of use, and vast ecosystem make it the go-to choice for developers. Whether you’re building a small website or a large-scale API, Express.js provides the necessary tools to streamline development.
Useful Links
You may like also:
- How To Create Secure MQTT Broker
- How To Enable Free HTTPS on your website
- How To Install Node.js on Ubuntu
- How to install MongoDB in ubuntu
- How to Install InfluxDB on Ubuntu
- What is Jinja
- IoT Operating Systems
Pingback: How To Install Django on Ubuntu - How To - IoTbyHVM
Pingback: Introduction of Socket.IO - A real-time web applications - IoTbyHVM
Pingback: Nodemon - Automatic Restart the node application - IoTbyHVM
Pingback: MEAN STACKS ? | Introducing the MEAN and MERN Stacks
Pingback: Nodemon - Automatic Restart the node application
Pingback: Nodemon - Automatic Restart the node application - CoolDigiBytes
Pingback: How to Send e-mail using NodeJS - CoolDigiBytes