Introduction to Express.js: The Popular Node.js Framework
Express.js is a lightweight and flexible web application framework for Node.js. It simplifies building web applications and APIs by providing a set of robust features, including routing, middleware support, and request handling. In this guide, we’ll explore the key features of Express.js, its benefits, and how to set up a basic Express server.
1. What is Express.js?
Express.js, or simply Express, is a minimal and fast Node.js framework designed for building web applications and RESTful APIs. It provides essential functionality without enforcing a strict structure, making it a popular choice for developers.
Key Features of Express.js
Simple and minimalistic: Provides core functionalities without unnecessary complexity.
Efficient routing: Handles multiple URL endpoints with ease.
Middleware support: Allows request processing and response modifications.
Templating engines: Supports Pug, EJS, and Handlebars for rendering dynamic content.
Error handling: Built-in mechanisms for managing errors and exceptions.
2. Setting Up Express.js
2.1 Prerequisites
Ensure Node.js and npm (Node Package Manager) are installed.
Check installation:
node -v # Check Node.js version
npm -v # Check npm version
2.2 Creating a New Node.js Project
Create a project folder:
mkdir express-app cd express-app
Initialize a new Node.js project:
npm init -y
This generates a
package.json
file to manage dependencies.
2.3 Installing Express.js
Run the following command to install Express.js:
npm install express
3. Creating a Basic Express Server
Create a new file named server.js
and add the following code:
const express = require('express'); // Import Express
const app = express(); // Initialize Express
const PORT = 3000; // Define the port
// Define a simple route
app.get('/', (req, res) => {
res.send('Hello, World! Welcome to Express.js.');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Running the Server
Start the server using:
node server.js
Visit http://localhost:3000/
in a browser, and you should see:
Hello, World! Welcome to Express.js.
4. Handling Routes in Express.js
Express makes routing simple by allowing different HTTP methods to handle requests.
Modify server.js
to include multiple routes:
app.get('/about', (req, res) => {
res.send('About Page: Learn more about Express.js.');
});
app.get('/contact', (req, res) => {
res.send('Contact Page: Reach us at contact@example.com.');
});
Testing the Routes
Visit
http://localhost:3000/about
→ Displays About Page.Visit
http://localhost:3000/contact
→ Displays Contact Page.
5. Using Middleware in Express.js
Middleware functions in Express.js allow processing requests and responses before they reach the route handler.
5.1 Built-in Middleware
Express provides built-in middleware like express.json()
and express.urlencoded()
for handling JSON and form data.
Modify server.js
to use middleware:
app.use(express.json()); // Enable JSON parsing
app.post('/data', (req, res) => {
res.send(`Received Data: ${JSON.stringify(req.body)}`);
});
Send a POST request with JSON data using Postman or cURL:
curl -X POST http://localhost:3000/data -H "Content-Type: application/json" -d '{"name": "John"}'
Expected response:
Received Data: {"name":"John"}
6. Serving Static Files with Express.js
Express can serve static files like HTML, CSS, and images using express.static()
.
6.1 Create a Public Folder
Inside your project, create a public
folder and add an index.html file:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Express</title>
</head>
<body>
<h1>Hello from Express.js!</h1>
</body>
</html>
6.2 Configure Static File Serving
Modify server.js
:
app.use(express.static('public'));
Testing Static File Serving
Visit http://localhost:3000/
→ The index.html page will be displayed.
7. Error Handling in Express.js
Express provides a built-in mechanism to handle errors.
7.1 Adding a 404 Error Handler
If a user accesses a non-existent route, return a 404 error:
app.use((req, res) => {
res.status(404).send('404 Not Found');
});
7.2 Adding a Global Error Handler
For handling server errors, add a middleware function:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Internal Server Error');
});
8. Best Practices for Using Express.js
Use Environment Variables: Store configuration settings (e.g., ports, database credentials) in a
.env
file.Enable CORS: Use
cors
middleware to allow cross-origin requests.Use a Logger: Tools like morgan help track incoming requests.
Organize Routes: Separate routes into different files for maintainability.
Implement Security Best Practices: Use helmet.js to protect against vulnerabilities.
9. Conclusion
Express.js simplifies web development with Node.js by providing a minimal, flexible, and powerful framework. You learned how to:
Install and set up Express.js
Create a basic server
Implement routing and middleware
Serve static files
Handle errors efficiently