Add routes
Make your server respond to different URLs
⏱ Est. ~8 min
01 · Read
Right now your server only responds to one URL: the root path /. If you visit localhost:3000/about or localhost:3000/anything-else, you'll get an error.
Real websites have many pages — home, about, contact, product pages, and many more. Each page has its own route — a URL path the server knows how to handle.
Adding routes is how you teach your server to respond with different content for different URLs. Each app.get() call creates a new route.
💡 Picture thisThink of routes like the reception desk at an office. Someone wants the sales department, reception sends them to one room. Someone wants customer service, they go to another. Your server is the receptionist, routes are the directions.
Key points
- Each app.get('/path', ...) creates a new route
- The path is the part of the URL after localhost:3000
- Different routes can return totally different content
- This is how every website serves different pages
02 · Real-machine exercise
Open your app.js in a text editor and add these two new routes. Put them after your existing app.get('/') route, but before the app.listen() line.
app.get('/about', (req, res) => {
res.send('This is the about page. I built this server myself!');
});
app.get('/contact', (req, res) => {
res.send('Contact me at: hello@mysite.com');
});03 · Real-machine exercise
Your server is still running the old code. To see the changes, you need to stop the server and restart it. Go to the terminal where the server is running, press Ctrl+C to stop it, then start it again.
node app.js
04 · Quiz
In app.get('/about', handler), what does /about represent?
- The name of the file to send
- The URL path that triggers this handler
- A folder on the computer
- A variable name
05 · Fill in the blank
In Express, app.get('/about', ...) creates a route that responds to the _____ path.
06 · Real-machine exercise
Now test your new routes! Open the browser and visit these two URLs: 1. http://localhost:3000/about — should show your about page text 2. http://localhost:3000/contact — should show your contact page text Also try http://localhost:3000 to confirm the original route still works.
http://localhost:3000/about
http://localhost:3000/contact
07 · Quiz
Your server has routes for /, /about, and /contact. A user visits http://localhost:3000/pricing. What happens?
- Express automatically creates a pricing page
- The server crashes with an error
- The server returns a "Cannot GET /pricing" error because no route matches that path
- The request gets redirected to the / route
Other lessons in this chapter
⚠ The full interactive experience needs JavaScript. Please enable it and reload.
※ This is an independent Traditional Chinese teaching project — not an official Anthropic product. Claude™ is a trademark of Anthropic, PBC.