Express Routes
An Express route is an address with the code that answers it. Each address on a site gets its own route.
A home route
This route answers the home address with one line.
app.get('/', (req, res) => {
res.send('Home page');
});A second route
This route answers the address /about.
app.get('/about', (req, res) => {
res.send('About page');
});Example
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.listen(3000, () => {
console.log('Server running on port 3000');
});Key points
- A route is an address with the code that answers it.
- app.get makes a route that answers GET requests.
- The first value of app.get is the address of the route.
- The second value is a function that runs when the address is asked for.
- res.send sends a reply and ends it.
- app.listen starts the Express server on a port.
- A route answers only its own address.
In this example, the first route answers the home address with Home page. The second route answers /about with About page. A visit to / answers Home page, and a visit to /about answers About page. The startup line prints Server running on port 3000.
Note
A visit to an address with no route gets a not found reply.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does app.get('/about', ...) do?