Basic

Routes and URLs

A route maps a URL to some code. Learn how Express matches paths like `/` and `/about`, reads the requested path, and returns different answers for each one.

About 2 min of reading

Data Flow

Express compares the requested URL to each registered route, picks the match, runs its handler, and sends the answer.
1 Browser requests /user/ada
↓
2 Express checks each route in order
↓
3 It matches /user/:name
↓
4 The :name parameter becomes 'ada'
↓
5 Handler builds the response
↓
6 Response is sent back to the browser
Why this works
HTTP methods matter

GET asks for data. There are other verbs too:

  • GET: read something.
  • POST: send new data (like a sign-up form).
  • PUT: replace existing data.
  • DELETE: remove data.

Express has a method for each:

app.post('/login', handler);

Choosing the right method is not optional, it is how the whole web understands what an action means.

Examples

Two routes, two answers

Add a second route. Now different links show different content:

app.get('/', (req, res) => {
  res.send('Home page');
});

app.get('/about', (req, res) => {
  res.send('About this app');
});

Visit / and /about. Each is handled by its own block of code. This is how multi-page websites are built, a route for every page. Clicking a link to /about simply asks the server for that path.

Route parameters

Some URLs carry data in the path. Use a colon to mark a parameter:

app.get('/user/:name', (req, res) => {
  const name = req.params.name;   // read the value from the URL
  res.send('Hello, ' + name + '!');
});

Open /user/ada and you see Hello, ada!. The :name part is captured and placed into req.params.name, so one route can answer for many users.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Project setup with npm
Previous Lesson
Project setup with npm
Next Lesson
Serving HTML pages
Serving HTML pages →