Request Handling and Routing

Routing maps incoming HTTP requests to specific application functions or handlers. Allowing different URLs to trigger different actions or return different content.

A Minimal Web Server

const http = require('http')

const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end('Hello, world!\n')
})

server.listen(3000, '127.0.0.1', () => {
  console.log('Server running at http://127.0.0.1:3000/')
})

Save as index.js and run it with node index.js. Visiting http://localhost:3000/anypage.html will return "Hello, world!".

Implementing Basic Routing

The below example adds more routes:

const http = require('http')

const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`)

  if (url.pathname === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' })
    res.end('Hello, world!')
  } else if (url.pathname === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/plain' })
    res.end('This is the about page.')
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' })
    res.end('Not found')
  }
})

server.listen(3000, () => {
  console.log('Server running at http://127.0.0.1:3000/')
})

This adds an /about page (http://localhost:3000/about) and handles 404 errors for incorrect URLs like http://localhost:3000/foo.

Using a Router

Web frameworks simplify route definition. Let's take Express.js as an example.

Install it with npm:

npm install --save express

Here's an Express.js equivalent:

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

app.get('/', (req, res) => {
  res.send('Hello, world!')
})

app.get('/about', (req, res) => {
  res.send('This is the about page.')
})

app.listen(3000, () => {
  console.log('Server listening on port 3000')
})

This achieves roughly the same functionality as the previous examples but with a cleaner, more organized structure.