Express.js Basics: A Beginner's Guide - Node.js Tutorial Series - part 10
Abdelhakim mohamed
Posted on September 26, 2024
Introduction:
Hey there! If you're new to Node.js, you've probably heard of Express.js—a lightweight, fast, and flexible framework for building web servers and APIs. In this guide, I'll walk you through the basics of Express, showing you how easy it is to get started.
Ready? Let's dive in!
1. Installing Express
First things first, let's install Express. Make sure you have Node.js and npm (Node's package manager) set up on your machine. Once you're good to go, open your terminal and run this command:
npm install express
Boom! You've just installed Express in your project. It's that simple.
2. Creating Your First Express Server
Now, let's build something! Here's how you can create a super simple Express server that listens for requests and responds with "Hello World" when someone visits your site.
const express = require('express'); // Import Express
const app = express(); // Initialize your Express app
app.get('/', (req, res) => { // Set up a route for GET requests to the root URL
res.send('Hello World'); // Send a response
});
app.listen(3000, () => { // Tell the app to listen on port 3000
console.log('Server is running on port 3000');
});
If you run this with node app.js
and open http://localhost:3000
in your browser, you'll see "Hello World." It's that easy to get a server up and running!
3. What’s Middleware?
You might have heard the term "middleware" thrown around a lot. Simply put, middleware is just a function that gets executed between a request being received and a response being sent.
Let’s look at a simple example:
app.use((req, res, next) => {
console.log('Request received');
next(); // Moves to the next middleware or route
});
In this case, every time a request is made, it logs "Request received" to the console. The next()
function is crucial here because it allows the request to continue to the next middleware function or route handler. Without it, the request would stop, and no response would be sent.
If you're interested in learning more about how middleware works in detail, check out Understanding Middleware in Express.js with Node.js. It covers different types of middleware, such as router-level, and error-handling middleware.
4. Routing: The Backbone of Your App
Routing is how you set up different URLs in your app. You already saw a basic route for the root (/
) path, but you can also handle other HTTP methods, like POST
, to deal with form submissions or data updates.
app.post('/submit', (req, res) => {
res.send('Form submitted!');
});
Now, when a user submits a form to /submit
, this route will handle it. You can create as many routes as you need—Express makes it easy!
5. Serving Static Files
What if you want to serve images, CSS files, or other static assets? Express has you covered! Just drop those files into a folder, like public
, and tell Express where to find them:
app.use(express.static('public'));
Now, any file inside the public
folder (like style.css
or an image) can be accessed directly by the browser.
6. Handling JSON Data
In modern apps, you'll often need to handle JSON data—maybe from a form or an API request. Express makes this super easy:
app.use(express.json()); // Add this middleware to parse JSON
app.post('/data', (req, res) => {
console.log(req.body); // Access the parsed JSON data
res.send('Data received!');
});
Now, when a POST
request with JSON data is sent to /data
, Express will automatically parse the JSON, and you can access it in req.body
. Simple, right?
Wrapping It All Up
And there you have it—a quick and easy introduction to Express.js! With just a few lines of code, you’ve learned how to:
- Install Express,
- Set up a basic server,
- Use middleware,
- Handle different routes,
- Serve static files,
- And work with JSON data.
Express is a powerful framework that makes building web servers and APIs fun and straightforward. As you get more comfortable, you can start exploring more advanced features like routers, error handling, or even integrating with a database.
Pro Tips for Your Express Journey
-
Use
nodemon
: It automatically restarts your server when you make changes. Just runnpm install -g nodemon
and usenodemon app.js
instead ofnode app.js
. - Structure your app: As your project grows, you'll want to organize your routes and controllers into separate files. This keeps your code clean and manageable.
I hope this guide helps you get started with Express! Keep experimenting, and before you know it, you’ll be building awesome web apps like a pro.
Happy coding!
Posted on September 26, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.