Express.js for Beginners: What It Is, How Routing Works, and Why Middleware Is Important ?

Express.js for Beginners: What It Is, How Routing Works, and Why Middleware Is Important ?

Ever wonder how websites handle all those user requests so smoothly? It’s no magic — it’s Express.js! 🚀 Whether you’re new to Node.js or just curious about building web apps, this guide will help you understand what Express.js is, how to use routing, and why middleware is a game-changer. Let’s dive in!

What Exactly is Express.js? 🤔

Express.js is like the trusty wingman of Node.js. Imagine you’re building a web app. You could write all the code yourself to handle server requests, responses, and manage all those tedious details. OR… you could use Express.js, which does all that dirty stuff for you!

Think of Express.js as the “waiter” at your favorite restaurant. 🍽️ When a guest (user) shows up, the waiter (Express.js) takes their order, passes it to the kitchen (your server-side code), and brings back the food (your response) quickly and efficiently.

How Does Express.js Work? ⚒

Express.js is a web framework that helps you build web applications and APIs using Node.js. It simplifies the process of managing server requests and responses, making it easier to build scalable web apps.

Let’s take a quick look at how easy it is to get started:

  1. Install Express:

First, make sure you have Node.js installed. Then, initia⚒lize a new project and install Express:

npm init -y
npm install express
  1. Create a Simple Server:

Now, create a file called app.js and add the following code:

const express = require('express'); // Import Express
const app = express(); // Create an Express application
const port = 3000; // Define the port

// Define a route for the homepage
app.get('/', (req, res) => {
  res.send('Hello, World!'); // Send a response
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});
  1. Run Your Server:
node app.js

Head over to your browser and visit http://localhost:3000, and voila! You should see "Hello, World!" pop up. 🎉 Congrats! You’ve just created your first Express server!

What is Routing in Express.js? 🛤️

Now that you know what Express.js is, let’s talk about routing.

Routing is like setting up a map for your web application. When users request different URLs, routing helps direct them to the right “destination” or functionality within your app.

How Routing Works in Express.js 🚦

Routing in Express.js is all about defining how your app should respond to different HTTP requests for various URLs. Let’s break down the most common types of HTTP requests:

  1. GET: Used to fetch data. Like asking, "Hey, what’s on the homepage?"

  2. POST: Used to create new data. Think of it as submitting a form — "Here’s my info, please save it!"

  3. PUT: Used to update existing data entirely. Imagine replacing an entire profile with new details.

  4. PATCH: Used to partially update existing data. Like changing just one field, such as your bio.

  5. DELETE: Used to remove data. As straightforward as deleting a comment.

Setting Up Basic Routes in Express.js:

Let’s add some routes to handle different types of HTTP requests:

const express = require('express');
const app = express();
const port = 3000;

// Handle GET request: Fetch data from the server
app.get('/', (req, res) => {
  res.send('Hello, GET request!');
});

// Handle POST request: Add new data to the server
app.post('/add', (req, res) => {
  res.send('New data has been added!');
});

// Handle PUT request: Replace existing data
app.put('/update', (req, res) => {
  res.send('Data has been updated!');
});

// Handle PATCH request: Update a part of existing data
app.patch('/modify', (req, res) => {
  res.send('Data has been partially modified!');
});

// Handle DELETE request: Remove data from the server
app.delete('/delete', (req, res) => {
  res.send('Data has been deleted!');
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

Why Routing Matters 🚀

Routing is crucial because it keeps your app organized and efficient. It’s like a traffic cop guiding requests to the right place so that each request is handled appropriately. By defining routes for different actions, you can build a well-structured, scalable web app or API.

Middleware in Express.js:

Alright, now that we’ve covered routing, let’s talk about middleware. It's like a secretary for your app. Everything goes through it and gets filtered.

What is Middleware? 🤔

Middleware is like the friendly bouncer at a club. 🕺 Before letting anyone in (processing requests), it checks if they’re on the guest list (authorized), makes sure they’re dressed appropriately (valid data), and maybe even offers them a drink (adds some extra info) before passing them through.

a person is sitting in a car with the words i 'm on it written on the back .

Technically, middleware is any function that has access to the request (req), response (res), and the next function (next) in the request-response cycle of your app. Middleware can:

  • Modify requests or responses.

  • End a request-response cycle.

  • Pass control to the next middleware function using next().

Why Middleware is Essential 🛠️

Middleware helps you do tons of important things:

  1. Logging: Track every request that comes to your server.

  2. Authentication: Check if a user is logged in before accessing certain routes.

  3. Error Handling: Catch and handle errors smoothly.

  4. Serving Static Files: Serve images, CSS, JavaScript, and more.

Serving Static Files with Middleware 🖼️

One of the common uses of middleware in Express.js is to serve static files, like images, CSS stylesheets, and JavaScript files. Static files are files that don't change based on user input, like the homepage logo or the styles for your site.

Express has a built-in middleware function, express.static(), to serve static files directly. Let’s see how it works!

  1. Create a Folder for Static Files:

First, create a directory in your project folder to store all your static assets. Let’s name it public.

/my-express-app
  /public
    - style.css
    - script.js
    - logo.png
  - app.js
  1. Serve Static Files Using Middleware:

Next, use the express.static middleware to serve the files in the public directory. Add the following line to your app.js:

const express = require('express');
const app = express();
const port = 3000;

// Middleware to serve static files from the 'public' directory
app.use(express.static('public'));

// Example route
app.get('/', (req, res) => {
  res.send('Hello, Express with Middleware!');
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});
  1. How This Works:

When you use express.static('public'), Express automatically serves files from the public directory when users request them.

For example:

This approach makes it incredibly easy to serve your static files without writing any extra code to handle each file type!

Create Your Own Middleware:

You can also create your own custom middleware to handle anything your app needs! Here’s a simple example of authentication middleware:

const checkAuth = (req, res, next) => {
  if (req.query.auth === 'true') {
    console.log('User authenticated!');
    next(); // User is authenticated, pass control to the next middleware/route
  } else {
    res.status(401).send('Not authorized!'); // User not authenticated, send an error
  }
};

// Use the custom middleware on a route
app.get('/dashboard', checkAuth, (req, res) => {
  res.send('Welcome to your dashboard!');
});

In this example:

  • The checkAuth middleware checks if the user is authenticated by looking at a query parameter.

  • If authenticated (auth=true), it calls next() to proceed to the dashboard route.

  • If not, it returns a 401 error with a "Not authorized!" message.

Handling User Input with Body Parsers 📥

When building web applications, you often need to handle data sent by users through forms or API requests. This is where body parsers come into play.

Handling User Input with Body Parsers 📥

A body parser is middleware that reads the body of incoming requests and makes it accessible through req.body. This is especially useful for handling POST, PUT, and PATCH requests where you need to process data sent by the client.

Using Body Parser Middleware

Express.js used to have its own body-parser module, but since version 4.16.0, it comes with a built-in body parser. Here’s how you can use it:

Installing Body-Parser:

If you prefer using the standalone body-parser module, you can install it:

npm install body-parser

Integrating Body-Parser:

Add the body parser middleware to your Express app to handle JSON and URL

const express = require('express');
const bodyParser = require('body-parser'); // Import body-parser

const app = express();
const port = 3000;

// Middleware to parse JSON bodies
app.use(bodyParser.json());

// Middleware to parse URL-encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));

// Example route to handle POST request
app.post('/submit', (req, res) => {
  const userData = req.body; // Access parsed data from the request body
  res.send(`User data received: ${JSON.stringify(userData)}`);
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

With this setup, you can handle incoming JSON and URL-encoded data with ease. For example, when a user submits a form with their name and email, you can access these values through req.body.name and req.body.email.

In a Nutshell 🥜

And there you have it — a full rundown of Express.js, from understanding what it is and how routing works, to mastering middleware and handling user input with body parsers. Express.js is like the Swiss Army knife 🔪 of Node.js, helping you build fast, flexible, and powerful web apps and APIs.

So go ahead, give Express.js a try, and see how these tools can make your development process faster, easier, and more fun! 🚀