HTTP and APIs · Lesson 10 of 18
Routing and JSON bodies
Choose handlers by method and pathname, and read bounded request bodies.
A route is a (method, pathname) pair. Use new URL(req.url, base) to separate pathname from query. A Node request body is a stream: collect chunks with a size limit, then JSON.parse inside try/catch. GET normally has no body, while POST creates a resource.
method + URL
Router matches
Read/validate JSON
handler + status
const http = require("node:http")
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://localhost")
res.setHeader("content-type", "application/json")
if (req.method === "GET" && url.pathname === "/health") {
res.end(JSON.stringify({ ok: true }))
} else {
res.statusCode = 404
res.end(JSON.stringify({ error: "not found" }))
}
})
server.listen(0, async () => {
const base = "http://127.0.0.1:" + server.address().port
const a = await fetch(base + "/health")
const b = await fetch(base + "/missing")
console.log(a.status, (await a.json()).ok, b.status)
server.close()
})A readJson(req) helper should reject oversized bodies with 413, malformed JSON with 400, and check content type. Match the pathname rather than the whole query string. Parameters such as /tasks/42 need parsing, conversion and validation.
Quick question
What status should malformed client JSON receive?
Exercise
Write route(method,path) returning list for GET /tasks, create for POST /tasks, otherwise not-found. Print all three.
Expected output: list create not-found
function route(method, path) {
}
console.log(route("GET", "/tasks"), route("POST", "/tasks"), route("GET", "/x"))Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.