Express.js
Express.js, often simply referred to as Express, is a web application framework for Node.js, a server-side JavaScript runtime. It is one of the most widely used and popular frameworks for building web applications and APIs with Node.js.
Express.js simplifies the process of creating robust and scalable web applications by providing a set of features and tools for handling routes, middleware, and HTTP requests and responses. It follows the model-view-controller (MVC) architectural pattern, allowing developers to structure their code in a modular way.
Key features of Express.js include:
Express.js is known for its lightweight nature, flexibility, and a large ecosystem of third-party middleware and extensions. It is often chosen by developers for building scalable and efficient web applications using the Node.js runtime.
?
Below is a simple example of an Express.js application that creates a basic server and handles a GET request:
First, make sure you have Node.js installed on your system.
Create a new directory for your project and navigate into it:
mkdir express-example
cd express-example
Initialize a new Node.js project using the following command:
npm init -y
Install Express as a dependency:
npm install express
Create a file named app.js and open it in a code editor. Add the following code:
// Import the Express module
const express = require('express');
// Create an instance of the Express application
const app = express();
// Define a route for the root path ("/")
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
// Set the server to listen on port 3000
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on https://localhost:${port}`);
});
This simple Express application does the following:
node app.js
Open your web browser and navigate to https://localhost:3000. You should see the message "Hello, Express!" displayed in your browser.
This is a very basic example to get you started. Express can be extended to handle more complex routing, middleware, and other features depending on the requirements of your web application.
Let's create a slightly more complex example that includes routing, middleware, and a basic template engine. We'll use the EJS (Embedded JavaScript) template engine for rendering dynamic content.
Install the EJS module:
领英推荐
npm install ejs
Update your app.js file with the following code:
const express = require('express');
const app = express();
const port = 3000;
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Middleware to log the timestamp for each request
app.use((req, res, next) => {
console.log(`Request received at ${new Date()}`);
next();
});
// Define routes
app.get('/', (req, res) => {
res.render('index', { message: 'Hello, Express with EJS!' });
});
app.get('/about', (req, res) => {
res.render('about');
});
// Serve static files from the "public" directory
app.use(express.static('public'));
// Handle 404 errors
app.use((req, res) => {
res.status(404).send("404 - Not Found");
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on https://localhost:${port}`);
});
Create a folder named views in your project directory. Inside the views folder, create two EJS template files: index.ejs and about.ejs. For example:
views/index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Express Example</title>
</head>
<body>
<h1><%= message %></h1>
</body>
</html>
views/about.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>About Us</title>
</head>
<body>
<h2>About Us</h2>
<p>This is a sample about page.</p>
</body>
</html>
Create a folder named public in your project directory. Inside the public folder, add a simple CSS file, for example:
public/style.css:
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 20px;
background-color: #f4f4f4;
}
h1, h2 {
color: #333;
}
Save the changes and restart the server using:
node app.js
Open your web browser and visit https://localhost:3000. You should see the "Hello, Express with EJS!" message. Also, try visiting https://localhost:3000/about to see the about page. The timestamp of each request will be logged in the console due to the middleware. The static CSS file will be applied to the pages as well.
This example demonstrates basic routing, middleware for logging, serving static files, and using the EJS template engine for rendering dynamic content.
Express.js offers several benefits, making it a popular choice for building web applications and APIs. Here are some of the key advantages:
Overall, Express.js is a powerful and flexible framework that strikes a balance between simplicity and extensibility, making it well-suited for a wide range of web development projects.
Author
Nadir Riyani is an accomplished and visionary Engineering Manager with a strong background in leading high-performing engineering teams. With a passion for technology and a deep understanding of software development principles, Nadir has a proven track record of delivering innovative solutions and driving engineering excellence. He possesses a comprehensive understanding of software engineering methodologies, including Agile and DevOps, and has a keen ability to align engineering practices with business objectives.??