No history yet

Introduction to Express.js

Meet Express.js

Think of the built-in http module in Node.js as a powerful engine. You can build a car with it, but you'd have to craft every piece from scratch, from the chassis to the steering wheel. Express.js is like a high-quality car kit. It gives you the frame, the wheels, and a dashboard, letting you focus on building the features that make your car unique, not reinventing the basics.

It’s often called a "micro-framework" because it provides the essentials for web development without unnecessary complexity.

Express is a minimal and flexible web application framework for Node.js. It doesn't impose a strict structure on you, but it provides a robust set of features to simplify building web servers and APIs. Let's get a basic server running.

// First, install express in your project directory:
// npm install express

// Then, in your index.js file:
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

In just a few lines, you have a web server. The app.get() method is our first look at routing. It tells the server what to do when it receives a GET request to the root URL (/). The req and res objects represent the HTTP request and response, which you've seen before with the http module.

Routing and Middleware

Routing is how an application’s endpoints (URIs) respond to client requests. You define routes by specifying an HTTP method and a URL path. We already saw app.get(), but there are methods for all HTTP verbs.

// A route for GET requests to /users
app.get('/users', (req, res) => {
  res.send('Got a GET request at /users');
});

// A route for POST requests to /users
app.post('/users', (req, res) => {
  res.send('Got a POST request at /users');
});

But what happens between the request and the response? That's where middleware comes in.

Middleware functions are the backbone of Express. They are functions that have access to the request (req), the response (res), and the next function in the application’s request-response cycle. The next function is a function that, when invoked, executes the next middleware in line.

A middleware function can perform tasks like logging requests, parsing the body of incoming requests, or checking for user authentication before passing the request to your route handler.

// This is a simple logger middleware function.
const myLogger = function (req, res, next) {
  console.log('LOGGED:', req.method, req.url);
  next(); // Pass control to the next middleware function
};

// To use it for all routes, we call app.use()
app.use(myLogger);

When you call app.use(myLogger), every single request that comes into your server will first pass through this logger function before it hits any of your specific route handlers like app.get('/').

Static Files and Templates

Web applications need to serve static files like images, CSS, and client-side JavaScript. Express has a built-in middleware for this called express.static.

Imagine you have a folder named public containing your CSS and images. You can make everything in that folder directly accessible via a URL.

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

// Now, if you have a file public/images/logo.png,
// it's accessible at http://localhost:3000/images/logo.png

For dynamic content, you'll often use a template engine. A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values and transforms the template into an HTML file sent to the client.

Express supports many popular template engines like Pug, EJS, and Handlebars. To use one, you first install it (npm install ejs), then tell Express to use it.

// Tell Express to use EJS as the view engine
app.set('view engine', 'ejs');

// A route that renders a view
app.get('/profile', (req, res) => {
  // Assumes you have a 'views/profile.ejs' file
  res.render('profile', { user: 'Ada Lovelace' });
});

Inside profile.ejs, you could then have HTML with a placeholder like <%= user %>, which EJS would replace with 'Ada Lovelace' before sending the final HTML to the browser.

Quiz Questions 1/5

What is the primary role of a middleware function in an Express.js application?

Quiz Questions 2/5

In Express, the code app.use(express.static('public')) is used for what purpose?

Express provides a clean and simple way to organize your web server's logic. By handling routing, middleware, and static files, it lets you focus on building the features of your application.