Session – 1
In this session, you will learn the fundamentals of Express.js, a popular web framework for Node.js. We’ll cover its core features and architecture, set up a basic Express.js application, explore its features and advantages, and work on an applied project to build a simple Express.js server that serves static files. We’ll also discuss best practices, practice exercises, LeetCode/HackerRank problems, and focus on understanding server frameworks in data structures and algorithms (DSA).
Table of Contents
- Introduction to Express.js
- Setting Up Your Environment
- Creating Your First Express.js Application
- Exploring Express.js Features
- Applied Project: Building a Simple Express.js Server
- Best Practices
- Practice Exercises
- LeetCode/HackerRank Problems
- Data Structures and Algorithms (DSA) Focus
1. Introduction to Express.js
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It simplifies server-side development by providing a suite of tools to handle HTTP requests, routing, middleware, and more.
Key Points:
- Minimal and Flexible: Offers basic functionalities without too much overhead.
- Routing: Manages different URL paths in your application.
- Middleware: Functions that handle various tasks during the request-response cycle.
2. Setting Up Your Environment
To get started with Express.js, you need to have Node.js and npm (Node Package Manager) installed.
Check Node.js and npm Installation:
- Open your terminal or command prompt.
- Run the following commands to check if Node.js and npm are installed:
node -v
npm -v
- If they are installed, you will see the version numbers. If not, download and install Node.js from nodejs.org.
Create a New Project Directory:
- In your terminal, create a new directory for your project:
mkdir myapp
cd myapp
Initialize a New Node.js Project:
- Initialize a new Node.js project in your directory:
npm init -y
- This will create a
package.json
file with default settings. - Open the
package.json
file in your preferred text editor. - Add the
"type": "module"
property. - Your
package.json
should look like this:
{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Install Express.js:
- Install Express.js using npm:
npm install express
3. Creating Your First Express.js Application
Create a file named app.js
and add the following code to set up a basic Express.js server:
import express from 'express'; // Import the Express module
const app = express(); // Create an instance of an Express application
const port = 2024; // Define the port number
// Define a route that handles GET requests to the root URL ('/')
app.get('/', (req, res) => {
res.send('Hello World! Welcome to 2024!');
});
// Start the server and listen on the specified port
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Run the Application:
- In your terminal, run the following command to start your server:
node app.js
Access the Application:
- Open a web browser and navigate to
http://localhost:2024
to see “Hello World! Welcome to 2024!” displayed.
4. Exploring Express.js Features
A. Routing
Routing in Express.js allows you to define different URL paths and handle various types of requests (GET, POST, PUT, DELETE).
Example:
app.get('/about', (req, res) => {
res.send('About Page - 2024');
});
app.post('/submit', (req, res) => {
res.send('Form Submitted - 2024');
});
Explanation:
app.get('/about', (req, res) => {...})
: Defines a route for the/about
URL that responds with “About Page – 2024”.app.post('/submit', (req, res) => {...})
: Defines a route for the/submit
URL that handles POST requests and responds with “Form Submitted – 2024”.
B. Middleware
Middleware functions have access to the request object (req
), the response object (res
), and the next middleware function in the application’s request-response cycle.
Example:
const logger = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Pass control to the next middleware function
};
app.use(logger); // Use the logger middleware
Explanation:
const logger = (req, res, next) => {...}
: Defines a middleware function that logs the HTTP method and URL of each request.app.use(logger);
: Registers the middleware function to be used by the application.
C. Template Engines
Template engines like Pug, EJS, or Handlebars can be used to render dynamic content. Here’s how to use Pug:
Install Pug:
npm install pug
Set Up Pug:
app.set('view engine', 'pug'); // Set Pug as the template engine
app.get('/hello', (req, res) => {
res.render('index', { title: 'Hey', message: 'Hello there! Welcome to 2024!' });
});
Example index.pug
:
doctype html
html
head
title= title
body
h1= message
Explanation:
app.set('view engine', 'pug');
: Configures the application to use Pug as the template engine.res.render('index', { title: 'Hey', message: 'Hello there! Welcome to 2024!' });
: Renders theindex.pug
template with the specified data.
D. Static Files
Serve static assets like HTML, CSS, and JavaScript files using express.static
.
Setup Static Middleware:
app.use(express.static('public')); // Serve static files from the 'public' directory
Project Structure:
myapp/
├── public/
│ ├── index.html
│ ├── styles.css
│ └── script.js
├── app.js
└── package.json
Example index.html
:
<!DOCTYPE html>
<html>
<head>
<title>My Express App - 2024</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Hello, Express! Welcome to 2024!</h1>
<script src="script.js"></script>
</body>
</html>
Explanation:
app.use(express.static('public'));
: Configures the application to serve static files from thepublic
directory.- The
public
directory contains static assets like HTML, CSS, and JavaScript files that can be directly accessed via URLs.
E. Error Handling
Express.js provides built-in mechanisms for error handling, allowing you to handle errors gracefully.
Example:
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error stack trace
res.status(500).send('Something broke in 2024!'); // Respond with a 500 status and error message
});
Explanation:
app.use((err, req, res, next) => {...})
: Defines an error-handling middleware function.console.error(err.stack);
: Logs the error stack trace to the console.res.status(500).send('Something broke in 2024!');
: Sends a 500 status code and an error message to the client.
5. Applied Project: Building a Simple Express.js Server
- Setup Static Middleware:
app.use(express.static('public'));
- Project Structure:
myapp/
├── public/
│ ├── index.html
│ ├── styles.css
│ └── script.js
├── app.js
└── package.json
Example index.html
:
<!DOCTYPE html>
<html>
<head>
<title>My Express App - 2024</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Hello, Express! Welcome to 2024!</h1>
<script src="script.js"></script>
</body>
</html>
Explanation:
app.use(express.static('public'));
: Configures the application to serve static files from thepublic
directory.- Create the project structure as outlined above, with
index.html
,styles.css
, andscript.js
in thepublic
directory. - The
index.html
file contains basic HTML content with references to a CSS file and a JavaScript file.
6. Best Practices
- Use Express’s built-in functionalities efficiently:
- Utilize middleware to handle repetitive tasks like logging, authentication, and error handling.
- Keep your code modular by splitting routes and middleware into separate files.
Modularizing Code:
- Create Separate Files for Routes:
- Create a directory named
routes
and add a fileindex.js
:
- Create a directory named
import express from 'express';
const router = express.Router();
router.get('/', (req, res) => {
res.send('Home Page - 2024');
});
router.get('/about', (req, res) => {
res.send('About Page - 2024');
});
module.exports = router;
- In your
app.js
, use the routes:
const routes = require('./routes/index');
app.use('/', routes);
Explanation:
- Creating separate files for routes and middleware makes your code more organized and maintainable.
- The
routes/index.js
file defines routes for the home and about pages. - In
app.js
, the routes are registered usingapp.use('/', routes);
.
7. Practice Exercises
- Create a Basic Express.js Application:
- Set up routes to handle different types of requests.
- Implement middleware for logging and error handling.
- Add More Routes and Middleware:
- Create additional routes for different pages or functionalities.
- Use middleware to process requests before they reach the route handlers.
8. LeetCode/HackerRank Problems
What are LeetCode and HackerRank?
LeetCode and HackerRank are popular online platforms that provide a vast array of coding problems for practice. These platforms are widely used by developers to improve their programming skills, prepare for technical interviews, and understand various concepts in computer science.
- LeetCode: Known for its extensive library of coding problems categorized by difficulty and topic. It is commonly used for practicing algorithmic and data structure problems.
- HackerRank: Offers a broad range of coding challenges, including algorithms, data structures, databases, and more. It is known for its interactive coding environment and contests.
Creating an Account:
LeetCode:
- Visit the LeetCode Website:
- Go to LeetCode’s website.
- Click on “Sign Up”:
- On the top right corner of the homepage, click on the “Sign Up” button.
- Choose a Sign-Up Method:
- You can sign up using your email address, Google account, Facebook account, or LinkedIn account.
- Enter Your Information:
- If you choose to sign up with an email, enter your email address and create a password.
- If using a social account, follow the prompts to link your social media account.
- Verify Your Email:
- If you signed up with an email address, you will receive a verification email. Click on the verification link in the email to activate your account.
- Complete Your Profile:
- Once logged in, you can complete your profile by adding additional information such as your name, profile picture, and bio.
HackerRank:
- Visit the HackerRank Website:
- Go to HackerRank’s website.
- Click on “Sign Up”:
- On the top right corner of the homepage, click on the “Sign Up” button.
- Choose a Sign-Up Method:
- You can sign up using your email address, Google account, Facebook account, or LinkedIn account.
- Enter Your Information:
- If you choose to sign up with an email, enter your email address and create a password.
- If using a social account, follow the prompts to link your social media account.
- Verify Your Email:
- If you signed up with an email address, you will receive a verification email. Click on the verification link in the email to activate your account.
- Complete Your Profile:
- After logging in, you can complete your profile by adding additional information such as your name, skills, and profile picture.
Developer Tasks:
- Search for problems related to setting up web servers and handling HTTP requests: This will help you understand the underlying principles of server-side development.
- Solve basic server-side setup problems: These problems will reinforce your understanding of Express.js and its core functionalities.
9. Data Structures and Algorithms (DSA) Focus
What are Data Structures and Algorithms?
Data Structures and Algorithms (DSA) are fundamental concepts in computer science that deal with organizing and processing data efficiently. Understanding DSA is crucial for solving complex programming problems and building efficient software.
Data Structures:
- Arrays, Linked Lists, Stacks, Queues: Basic structures to store and manage data.
- Trees, Graphs: Advanced structures for hierarchical and networked data.
Algorithms:
- Sorting, Searching: Basic algorithms to manipulate data.
- Dynamic Programming, Greedy Algorithms: Techniques to solve complex problems.
Developer Tasks:
- Understanding server frameworks: Focus on how they handle requests, routes, and middleware. This knowledge is crucial for developing efficient and scalable server-side applications.
- Implement basic data structures and algorithms in Node.js: Practice implementing and using different data structures and algorithms in your Express.js applications to handle data more efficiently.
By following this structured approach, you can systematically learn and understand the fundamentals of Express.js, its core features, and best practices for building scalable web applications. Additionally, practicing on LeetCode and HackerRank will enhance your problem-solving skills and DSA knowledge, making you a well-rounded developer.