
Getting Started With Express.js
Hey Devs!
Ready to level up your Node.js skills? Now that you have Node.js set up, it's time to build web applications and APIs more efficiently. Today, we'll dive into Express.js, the most popular web framework for Node.js.
Table of Contents |
---|
What is Express.js? |
Setting Up Your Express Project |
Your First Express Server |
Understanding Routing |
Serving Static Files |
Essential Middleware: Nodemon |
Additional Tips |
Introduction
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies the process of building servers and APIs, allowing you to write cleaner, more organized code without having to reinvent the wheel for common web development tasks. Think of it as a powerful toolkit that sits on top of Node.js to make your life as a developer much easier.
What is Express.js?
At its heart, Express is a routing and middleware web framework that has minimal functionality of its own: an Express application is essentially a series of middleware function calls. It builds upon Node.js's http
module to handle requests and responses with ease.
Key Benefits of Express.js:
- Fast and Minimalist: It's unopinionated, meaning it doesn't force a specific project structure on you, giving you the freedom to organize your code as you see fit.
- Simplifies Routing: Express provides a simple yet powerful way to manage how your application responds to client requests to different URLs (e.g.,
/home
,/about
,/contact
). - Middleware Integration: It has a fantastic middleware system that allows you to add functionalities like logging, authentication, and data parsing in a plug-and-play manner.
- Robust and Scalable: It's the de-facto standard for building backend services with Node.js and is used by countless companies, from startups to large enterprises.
Prerequisites
Before you begin, ensure you have the following:
- Node.js and npm installed: You should be comfortable with the concepts from our previous guide, "Getting Started with Node.js".
- A code editor like Visual Studio Code (VS Code).
- An active internet connection.
Step 1: Setting Up Your Express Project
Let's get a new project up and running.
Create a project folder:
Open your terminal or command prompt and create a new directory for your Express application.
mkdir my-express-app
cd my-express-app
Initialize the project with npm:
Just like with our Node.js project, we'll create a package.json
file.
npm init -y
Install Express:
Now, let's install the Express framework as a dependency for our project.
npm install express
This command downloads Express and adds it to the node_modules
folder and your package.json
file. Your project is now ready for some Express code!
Step 2: Your First Express Server
It's time to write the classic "Hello World" example, but with an Express twist.
Create a file:
Inside your my-express-app
folder, create a new file named app.js
.
Add code to app.js:
Open app.js
in your code editor and add the following code:
// app.js
// 1. Import the express library
const express = require('express');
// 2. Create an instance of an Express application
const app = express();
const port = 3000; // Define a port for our server to listen on
// 3. Define a "route" for the root URL
app.get('/', (req, res) => { //<- This is a get route you can similarly create a post route.
res.send('Hello from Express and Ujjwalit!');
});
// 4. Start the server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Explanation:
require('express')
imports the framework.express()
creates your application.app.get('/', ...)
is a route handler. It tells the server what to do when it receives aGET
request to the root URL (/
).req
(request) andres
(response) are objects that represent the incoming HTTP request and the outgoing HTTP response.res.send()
is an Express function that sends a response back to the client.app.listen()
starts the server and makes it listen for incoming connections on the specified port.
Run the server:
Go back to your terminal and run the script:
node app.js
Open your web browser and navigate to http://localhost:3000
. You should see the message: Hello from Express!
Step 3: Understanding Routing
Routing is how an application responds to a client request for a specific endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, etc.).
Let's add a couple more routes to app.js
.
Update app.js:
// ... (keep the existing code from above)
// Add a route for the /about page
app.get('/about', (req, res) => {
res.send('This is the About page.');
});
// Add a route for an API endpoint
app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: 'Daksh Dixit' },
{ id: 2, name: 'Our Awesome Reader-1' }
]);
});
// ... (keep the app.listen part at the bottom)
Restart your server (Ctrl+C
to stop, then node app.js
to start again) and try visiting:
http://localhost:3000/
-> "Hello from Express!"http://localhost:3000/about
-> "This is the About page."http://localhost:3000/api/users
-> You'll see a JSON response with a list of users.
See how easy that was? Express makes defining clean and readable routes a breeze.
Step 4: Serving Static Files
Web applications need to serve static files like HTML, CSS, images, and client-side JavaScript. Express has a built-in middleware for this called express.static
.
- Create a
public
folder inside yourmy-express-app
directory. - Inside the
public
folder, create a new file namedindex.html
.
Add code to public/index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Express App</title>
</head>
<body>
<h1>Welcome to my website!</h1>
<p>This is a real HTML file served by Express.</p>
</body>
</html>
Update app.js
to use the middleware:
Add this line to app.js
right after you create the app
instance.
const express = require('express');
const app = express();
const port = 3000;
// Tell Express to serve static files from the 'public' directory
app.use(express.static('public'));
// ... (keep your other routes and the app.listen call)
Now, restart your server and go to http://localhost:3000
. Instead of "Hello from Express!", you will see your index.html
page! The express.static
middleware automatically found and served the index.html
file for the root URL.
Useful Tips
nodemon for Auto-Reloading:
Constantly stopping and restarting the server is tedious. nodemon
automatically restarts your application when it detects file changes.
Install it globally:
npm install -g nodemon
Run your server with:
nodemon app.js
Now, every time you save a file, the server will restart automatically!
Using node --watch
(Node.js 18+):
If you're using a recent version of Node.js, you can use the built-in watch mode:
node --watch app.js
Beginner Tips
- Understand the Request/Response Cycle: Deeply understand the
req
andres
objects. They are the heart of every Express application. - Explore Middleware: Learn about other common middleware like
body-parser
(now built into Express asexpress.json()
andexpress.urlencoded()
) for handling form data. - Use a REST Client: Tools like Postman or the Thunder Client extension for VS Code are essential for testing your API routes (especially for POST, PUT, DELETE requests).
- Read the Official Docs: The Express documentation is excellent and very well-written.
- Structure Your App: As your app grows, look into common patterns for organizing your routes and logic into separate files and folders.
Conclusion
You've successfully built your first web server with Express.js, learned the basics of routing, and even served static files. This is a huge step forward! Express provides the foundation you need to build powerful, scalable, and maintainable web applications and APIs with Node.js.
Have fun coding with Express!
Enjoy the content here?
Sign up on our platform or join our WhatsApp channel here to get more hands-on guides like this, delivered regularly.
See you in the next blog. Until then, keep practicing and happy learning!
6 Reactions
0 Bookmarks