SyntaxStudy
Sign Up
Express.js Beginner 10 min read

Express Routing

Express routing determines how an application responds to a client request to a particular endpoint (URI) and HTTP method. Routes can be organized using Express Router for better code structure.

Example
const express = require('express')
const router = express.Router()

// In-memory data (use a database in production)
let posts = [
  { id: 1, title: 'Hello World', body: 'First post' },
  { id: 2, title: 'Express Routing', body: 'Learning routes' },
]

// GET all posts
router.get('/', (req, res) => {
  const { page = 1, limit = 10, search } = req.query
  let result = posts
  if (search) result = result.filter(p => p.title.includes(search))
  res.json({ data: result, total: result.length })
})

// GET single post
router.get('/:id', (req, res) => {
  const post = posts.find(p => p.id === parseInt(req.params.id))
  if (!post) return res.status(404).json({ error: 'Post not found' })
  res.json(post)
})

// POST create
router.post('/', (req, res) => {
  const post = { id: Date.now(), ...req.body }
  posts.push(post)
  res.status(201).json(post)
})

// DELETE
router.delete('/:id', (req, res) => {
  const id = parseInt(req.params.id)
  posts = posts.filter(p => p.id !== id)
  res.status(204).send()
})

module.exports = router

// In app.js:
// const postsRouter = require('./routes/posts')
// app.use('/api/posts', postsRouter)