Introduction
Imagine you're running a post office. Every letter or package needs to be routed to its destination. Express works similarly, acting as the routing system for your web server. In this guide, we will configure Express routes to handle client requests, building on your knowledge of Node's http package.
You'll learn how to handle the following HTTP request types:
- GET - Retrieve data
- POST - Submit new data
- PUT - Update existing data
- PATCH - Modify a subset of data
- DELETE - Remove data
Setting Up Express
Let’s begin by creating a simple Express application:
const express = require('express');
const app = express();
// Define routes
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.post('/users', (req, res) => {
res.send('User created!');
});
// Start the server
const port = 8081;
app.listen(port, () => console.log(`Listening on port ${port}...`));
Key Steps:
- Create the Express server using
express(). - Define routes with
app.get(),app.post(), etc. - Start the server with
app.listen().
Understanding Routes
A route in Express is like a traffic signal directing requests to the right path. Each route matches:
- Path: A URI, like
/users. - HTTP Method: One of GET, POST, PUT, DELETE, or PATCH.
Here's an example:
app.get('/welcome', (req, res) => {
res.send('Welcome to our site!');
});
The req (request) object provides details about the client's request, while the res (response) object allows you to send data back.
Dynamic Route Paths
Routes in Express can be dynamic:
- Strings:
'/users' - Regular Expressions:
'/ab+cd' - Arrays:
['/home', '/about']
Example:
let paths = ['/', '/about', '/contact'];
app.get(paths, (req, res) => {
res.send('This works for multiple paths!');
});
Designing Routes
Good route design makes your application intuitive. Consider these examples for a Twitter-like app:
| Path | HTTP Verb | Description |
|---|---|---|
| /tweets | GET | Retrieve all tweets |
| /tweets | POST | Create a new tweet |
| /tweets/:id | GET | Retrieve a tweet by ID |
Sending Responses
Use the res object to send responses:
res.send(): Sends plain text or HTML.res.json(): Sends JSON data.
Example:
app.get('/json', (req, res) => {
res.json({
message: 'Hello, JSON!',
status: 'success'
});
});
Testing Your Routes
To test your Express application:
- Run your app with
node app.js. - Visit
http://localhost:8081in a browser (for GET requests). - Use tools like Postman or Fetch API for other methods:
fetch('/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'NewUser' })
}).then(res => res.json()).then(console.log);
Real-World Applications
Express routes are foundational for:
- APIs: Serve JSON data to frontend applications.
- Websites: Render HTML pages or serve static files.
- Microservices: Create small, single-purpose services.
Example: A task management app could use routes like:
GET /tasks: List all tasks.POST /tasks: Add a new task.DELETE /tasks/:id: Remove a task by ID.