This tutorial aims to introduce you to the Express framework, a flexible, minimalist web application framework for Node.js. You'll learn how to set up an Express application and create a simple server.
By the end of this tutorial, you'll be able to:
- Install Express via npm
- Create a basic Express app
- Understand the fundamental concepts of Express, such as routing and middleware
Express can be installed via npm (Node Package Manager). To add it to your project, navigate to your project directory in your terminal and type:
npm install express --save
To start, create a new file, app.js
, in your project's root directory. Here's a simple Express application:
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}`)
});
const express = require('express');
- This imports the Express module.const app = express();
- This creates an instance of an Express application.app.get('/', (req, res) => {...});
- This is a route definition. When a GET request is made to the root of the app, the callback function is called.app.listen(port, ()=>{...});
- This makes the app listen for requests on the specified port.Express uses routes to determine how an application responds to client requests. Here's an example:
app.get('/about', (req, res) => {
res.send('About Page')
});
app.get
is the method, corresponding to HTTP's GET.'/about'
is the path on the server.(req, res) => {...}
is the handler function, executed when the route is matched.The expected output when you navigate to 'http://localhost:3000/about' would be the text 'About Page'.
Middleware are functions that process incoming requests. Here's an example of a middleware function:
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
app.use
is a method to use a middleware function.(req, res, next) => {...}
is the middleware function. It logs the current time and passes control to the next middleware function.In this tutorial, you've learned how to:
- Install Express
- Create a basic Express app
- Understand routing and middleware in Express
To further your understanding of Express, try building a simple application that uses different HTTP methods and multiple routes.
Create an Express server that responds with "Hello, Express!" when a GET request is made to the homepage.
app.get('/', (req, res) => {
res.send('Hello, Express!')
});
Create a middleware that logs the details of every request (method, path, and time).
app.use((req, res, next) => {
console.log(`Method: ${req.method}, Path: ${req.path}, Time: ${Date.now()}`);
next();
});
These exercises will help you get a feel for building with Express. Keep experimenting with different types of requests, routes, and middleware.