Express.js, often referred to as Express, is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. In this tutorial, we’ll guide you through the basics of Express.js, including installation, creating routes, middleware, and more.
Table of Contents
- What is Express.js?
- Why Use Express.js?
- Installing Express.js
- Creating a Basic Express App
- Understanding Routes
- Using Middleware
- Templating with EJS
- Building a REST API
- Frequently Asked Questions (FAQs)
What is Express.js?
Express.js is a popular Node.js framework that simplifies the creation of web applications. It provides a structured approach to building applications by defining routes, middleware, and more. Express.js is lightweight and highly customizable, making it a great choice for both small and large projects.
Why Use Express.js?
- Lightweight: Express.js is minimal, allowing developers to add only what they need.
- Flexible: It supports various templating engines and middleware.
- Community: A large community and extensive documentation make it easy to find help and resources.
Installing Express.js
Before you can use Express.js, you need to install it. We’ll use npm (Node Package Manager) for installation.
Step 1: Install Node.js and npm
If you haven’t already installed Node.js and npm, download and install them from the Node.js official website.
Step 2: Create a New Project
Create a new directory for your project and initialize it using npm.
mkdir my-express-app
npm init -y
Step 3: Install Express.js
Install Express.js as a dependency.
npm install express
Creating a Basic Express App
Let’s create a simple Express application that listens on port 3000 and returns a greeting message.
Step 1: Create the App File
Create a file named app.js
in your project directory.
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Step 2: Run the Application
Run the application using the following command:
node app.js
Open your browser and visit http://localhost:3000
. You should see a greeting message.
Understanding Routes
In Express.js, routes determine how your application responds to different HTTP requests. Let’s explore some common HTTP methods.
GET Request
A GET request is used to retrieve data from the server.
app.get('/', (req, res) => {
res.send('Welcome to my Express.js App!');
});
POST Request
A POST request is used to send data to the server.
app.post('/submit', (req, res) => {
res.send('Data received!');
});
PUT Request
A PUT request is used to update existing data.
app.put('/update', (req, res) => {
res.send('Data updated!');
});
DELETE Request
A DELETE request is used to remove data.
app.delete('/delete', (req, res) => {
res.send('Data deleted!');
});
Using Middleware
Middleware functions are used to process requests before they reach the route handlers. They can perform tasks like logging, authentication, and more.
Built-in Middleware
Express.js provides several built-in middleware functions.
Serving Static Files
Use express.static
to serve static files like HTML, CSS, and JavaScript.
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static('public'));
Create a public
directory and add an index.html
file.
<!DOCTYPE html>
<html>
<head>
<title>Static File Example</title>
</head>
<body>
<h1>Welcome to Static File Example</h1>
</body>
</html>
Parsing JSON Data
Use express.json()
to parse JSON data from incoming requests.
app.use(express.json());
app.post('/submit', (req, res) => {
console.log(req.body);
res.send('Data received!');
});
Templating with EJS
EJS (Embedded JavaScript) is a popular templating engine for Node.js applications. It allows you to generate HTML markup dynamically using JavaScript.
Step 1: Install EJS
Install EJS as a dependency.
npm install ejs
Step 2: Configure EJS in Express
Update your app.js
file to use EJS as the templating engine.
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index', { title: 'Welcome to EJS!' });
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Step 3: Create an EJS Template
Create a views
directory and add an index.ejs
file.
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1>Welcome to EJS Templating</h1>
</body>
</html>
Building a REST API
Express.js is widely used for building RESTful APIs. Let’s create a simple API for managing users.
Step 1: Define the API Routes
Update your app.js
file to include the API routes.
const express = require('express');
const app = express();
app.use(express.json());
const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' },
];
// Get all users
app.get('/api/users', (req, res) => {
res.send(users);
});
// Get a single user
app.get('/api/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.send(user);
});
// Create a new user
app.post('/api/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name,
};
users.push(newUser);
res.send(newUser);
});
// Update a user
app.put('/api/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');
user.name = req.body.name;
res.send(user);
});
// Delete a user
app.delete('/api/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === parseInt(req.params.id));
if (index === -1) return res.status(404).send('User not found');
const deletedUser = users.splice(index, 1);
res.send(deletedUser);
});
app.listen(3000, () => {
console.log('API is running on http://localhost:3000');
});
Step 2: Test the API
You can use tools like Postman or curl to test your API endpoints.
GET all users
curl http://localhost:3000/api/users
GET a single user
curl http://localhost:3000/api/users/1
POST a new user
curl -X POST -H "Content-Type: application/json" -d "{\"name\": \"Alice Johnson\"}" http://localhost:3000/api/users
PUT update a user
curl -X PUT -H "Content-Type: application/json" -d "{\"name\": \"Bob Wilson\"}" http://localhost:3000/api/users/1
DELETE a user
curl -X DELETE http://localhost:3000/api/users/1
Frequently Asked Questions (FAQs)
Q: What is Express.js?
A: Express.js is a Node.js framework used for building web applications and APIs.
Q: Why should I use Express.js?
A: Express.js is lightweight, flexible, and provides a robust set of features for building applications.
Q: How do I install Express.js?
A: You can install Express.js using npm with the command npm install express
.
Q: What is middleware in Express.js?
A: Middleware functions are used to process requests before they reach the route handlers. They can perform tasks like logging, authentication, and more.
Q: How do I create a REST API with Express.js?
A: You can create a REST API by defining routes for different HTTP methods (GET, POST, PUT, DELETE) and handling the requests accordingly.
Conclusion
Express.js is a powerful and flexible framework for building web applications and APIs. By following this tutorial, you should now have a good understanding of how to create routes, use middleware, and build a REST API using Express.js. Keep practicing and exploring the framework to become more proficient in using it for your projects.