Thuta Learning
IntermediateWeb Developmentbeginner

Express Routing

Relax. We'll talk through this in plain words — no textbook voice.

Routing is about deciding what response the server sends back, based on which URL the user/client calls. In Express, you write routes using the pattern app.METHOD(PATH, HANDLER).

javascript
const express = require('express');
const app = express();

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

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

app.get('/products/:id', (req, res) => {
  res.send(`Product ID is ${req.params.id}`);
});

app.post('/login', (req, res) => {
  res.send('Login route received a POST request');
});

app.listen(3000, () => console.log('Routing demo running on port 3000'));

/products/:id, :id is the route parameter. If you go to /products/15 in the browser, req.params.id will be 15.

You should see
GET http://localhost:3000/products/15 Product ID is 15

Info

GET requests are mostly used for reading data, and POST requests for sending data. Form submits, logins, and creating items usually use POST.

Easy traps

  • Typing a URL into the browser's address bar always sends a GET request. If you want to test a POST route, use Postman, Thunder Client, fetch, a form submit, or something similar.

Exercise

Use routing to structure things like e-commerce product pages, user profile pages, blog detail pages, and admin action endpoints.

You'll know it worked when:

Express Routing | Thuta Learning