Understanding Multiple Routes
Swipe to show menu
An application usually needs more than one route. Each route handles a different URL and returns a different response.
You can define multiple routes in the same server:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Home page');
});
app.get('/about', (req, res) => {
res.send('About page');
});
app.get('/contact', (req, res) => {
res.send('Contact page');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Each route has its own path. When a request comes in, Express checks the path and runs the matching route.
For example:
'/': home page;'/about': about page;'/contact': contact page.
If a route is not defined, Express will not know how to handle the request.
This is how applications serve different content based on the URL.
Everything was clear?
Thanks for your feedback!
Section 1. Chapter 4
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Section 1. Chapter 4