SyntaxStudy
Sign Up
Express.js Basic Routing with app.get and app.post
Express.js Beginner 1 min read

Basic Routing with app.get and app.post

Express routing maps HTTP methods and URL patterns to handler functions. The four most common methods mirror HTTP verbs: `app.get()`, `app.post()`, `app.put()`, and `app.delete()`. Each accepts a path string (or regex) and one or more handler callbacks. Route paths support exact strings, string patterns with wildcards, and full regular expressions. Query strings are not part of the path — they are parsed automatically into `req.query`. Named URL segments prefixed with `:` become properties of `req.params`. When multiple handlers are supplied to a single route, they form a mini-pipeline. Each must call `next()` to pass control forward or send a response to end the chain. This pattern is useful for attaching per-route validation or authentication without global middleware.
Example
const express = require('express');
const app = express();
app.use(express.json());

// GET  /users          → list all users
app.get('/users', (req, res) => {
    // req.query.page, req.query.limit available here
    const { page = 1, limit = 20 } = req.query;
    res.json({ page: +page, limit: +limit, users: [] });
});

// GET  /users/:id      → single user
app.get('/users/:id', (req, res) => {
    const { id } = req.params; // string
    res.json({ id, name: 'Alice' });
});

// POST /users          → create user
app.post('/users', (req, res) => {
    const { name, email } = req.body;
    if (!name || !email) {
        return res.status(422).json({ error: 'name and email required' });
    }
    res.status(201).json({ id: 42, name, email });
});

// DELETE /users/:id
app.delete('/users/:id', (req, res) => {
    res.status(204).send();
});

app.listen(3000);