Servers and environment
Route requests by method and URL
Read the incoming method and URL, choose a handler, and return an explicit status and content type for every path.
8 minute lesson
The request object provides the HTTP method, URL, and headers.
Parse request.url against a base URL so the pathname and query string are separate:
import { createServer } from 'node:http'
function sendJson(response, status, value, headers = {}) {
response.writeHead(status, {
'content-type': 'application/json; charset=utf-8',
...headers,
})
response.end(JSON.stringify(value))
}
const server = createServer((request, response) => {
const url = new URL(request.url, 'http://localhost')
if (url.pathname === '/notes' && request.method === 'GET') {
return sendJson(response, 200, { notes: [] })
}
if (url.pathname === '/notes') {
return sendJson(
response,
405,
{ error: 'Method not allowed' },
{ allow: 'GET, POST' }
)
}
return sendJson(response, 404, { error: 'Not found' })
})
Match both method and pathname. A query such as /notes?limit=10 still has pathname /notes; read url.searchParams separately and validate every value.
Use status codes to describe the failure precisely:
404 Not Found: this pathname does not identify a route405 Method Not Allowed: the pathname exists, but not for this method400 Bad Request: the route exists, but the submitted syntax or values are invalid
A 405 response should include an Allow header listing supported methods. Return immediately after ending a response so later router code cannot write headers or a second body.
Set Content-Type on success and error responses. JSON should normally include charset=utf-8. Do not return an HTML stack trace to an API client.
Routing selects a handler; it does not establish authorization. A valid /notes/42 match must still check whether the caller may read note 42.
Unexpected handler failures need a final error boundary. Log diagnostic context on the server and return a generic 500 only if headers have not already been sent. Once a streamed response has begun, the safe recovery can be to close that response instead.
Your action is to add POST /notes, validate one query parameter, and send requests covering 200, 400, 404, and 405. Verify each status, body content type, and Allow header.
Lesson completed