Node.js - Express Framework

Hello, aspiring programmers! Today, we're going to embark on an exciting journey into the world of Node.js and the Express framework. As your friendly neighborhood computer science teacher, I'm thrilled to guide you through this adventure. Don't worry if you've never written a line of code before – we'll start from the very beginning and work our way up together.

Node.js - Express Framework

What is Express?

Before we dive in, let's talk about what Express actually is. Imagine you're building a house. You could start from scratch, making your own bricks and cutting your own wood. Or, you could use pre-made materials that make the job easier and faster. Express is like those pre-made materials, but for web applications. It's a framework that provides a robust set of features for web and mobile applications, making it easier and faster to build web applications with Node.js.

Installing Express

Let's start by installing Express. First, make sure you have Node.js installed on your computer. If you don't, head over to the official Node.js website and download it.

Once Node.js is installed, open your terminal (or command prompt if you're on Windows) and type the following command:

npm install express

This command uses npm (Node Package Manager) to install Express. Think of npm as a magical toolbox that contains all sorts of useful tools (called packages) that we can use in our Node.js projects.

Hello World Example

Now that we have Express installed, let's create our very first Express application. We'll start with the classic "Hello, World!" example.

Create a new file called app.js and type in the following code:

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}`);
});

Let's break this down:

  1. We import the Express module and create an Express application.
  2. We define a port number (3000 in this case).
  3. We set up a route for the root URL ('/') that sends "Hello, World!" as a response.
  4. We tell our application to listen on the specified port.

To run this application, go to your terminal, navigate to the directory containing app.js, and run:

node app.js

Now, open your web browser and go to http://localhost:3000. You should see "Hello, World!" displayed on the page. Congratulations! You've just created your first Express application!

Application Object

In our previous example, we created an Express application object:

const app = express();

This app object is central to how we use Express. It has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering a template engine, and more.

Here are some of the most commonly used methods of the app object:

Method Description
app.get() Routes HTTP GET requests to the specified path with the specified callback functions
app.post() Routes HTTP POST requests to the specified path with the specified callback functions
app.use() Mounts the specified middleware function or functions at the specified path
app.listen() Binds and listens for connections on the specified host and port

Basic Routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Let's expand our application to include more routes:

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

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

app.get('/about', (req, res) => {
  res.send('This is the about page');
});

app.post('/submit', (req, res) => {
  res.send('Got a POST request');
});

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

In this example, we've added two new routes:

  • A GET route for '/about' that returns "This is the about page"
  • A POST route for '/submit' that returns "Got a POST request"

To test the POST route, you'll need a tool like Postman, or you can create an HTML form that submits to this route.

Serving Static Files

Often, you'll want to serve static files like images, CSS files, and JavaScript files. Express provides a built-in middleware function express.static for this purpose.

Let's create a directory called public in our project folder, and put an image file (let's say cat.jpg) in it. Then, modify our app.js like this:

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

app.use(express.static('public'));

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

app.get('/cat', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'cat.jpg'));
});

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

In this example, we've done two things:

  1. We've used app.use(express.static('public')) to serve static files from the 'public' directory.
  2. We've added a new route '/cat' that sends the cat.jpg file as a response.

Now, you can access your cat image directly at http://localhost:3000/cat.jpg, or through the '/cat' route we defined.

And there you have it! We've covered the basics of Express, from installation to serving static files. Remember, learning to code is like learning a new language – it takes practice and patience. Don't be discouraged if you don't understand everything right away. Keep experimenting, keep building, and most importantly, keep having fun!

In our next lesson, we'll dive deeper into Express middleware and more advanced routing techniques. Until then, happy coding!

Credits: Image by storyset