Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Routes and HTTP methods

A route connects an address and an HTTP method to a function that builds the response. Such a function is called a handler. An HTTP method is the kind of request: GET reads data, POST creates, PUT and PATCH change, DELETE removes.

A basic route

For now we write routes right in src/app.js, before the export default app line:

// src/app.js
app.get('/posts', (req, res) => {
  res.send('List of posts');
});

Open http://localhost:3000/posts and the browser shows "List of posts". The handler receives two objects: req — the request, res — the response.

Application methods

Every HTTP method has a method with the same name in lower case. One address can answer different methods differently:

// src/app.js
app.get('/posts', (req, res) => {
  res.send('List of posts');
});
 
app.post('/posts', (req, res) => {
  res.send('Post created');
});
 
app.put('/posts/1', (req, res) => {
  res.send('Post 1 replaced');
});
 
app.patch('/posts/1', (req, res) => {
  res.send('Post 1 updated');
});
 
app.delete('/posts/1', (req, res) => {
  res.send('Post 1 deleted');
});

When you type an address, the browser always sends GET. Other methods are tested with the curl utility in the terminal:

curl http://localhost:3000/posts
curl -X POST http://localhost:3000/posts
curl -X DELETE http://localhost:3000/posts/1

The terminal shows the answers "List of posts", "Post created" and "Post 1 deleted".

All methods at once

app.all() matches any method. It is used rarely — for example, to answer everything the same way at an old address:

// src/app.js
app.all('/old-blog', (req, res) => {
  res.send('The blog has moved to /posts');
});

Reaching a route from a page

A link in HTML always sends GET, and a form sends GET or POST:

<a href="/posts">All posts</a>
 
<form method="post" action="/posts">
  <button>Create</button>
</form>

Clicking the link calls the app.get('/posts') route, pressing the button calls app.post('/posts'). The PUT, PATCH and DELETE methods are sent by programs and scripts, for example fetch() in the browser.

Route order

Express checks routes in the order they were added and calls the first match. If none matches, the client gets a 404 response "Cannot GET /address".

Common mistake

Addresses are compared ignoring case and the trailing slash: /posts, /Posts and /posts/ reach the same route. But /post and /posts are different addresses. If a page answers 404, first compare the address in the route and in the link letter by letter.

Thanks for reading!

Donate to the site — we work hard for you.