HTTP and APIs · Lesson 9 of 18
Your first HTTP server
Receive a request and send status, headers and a body with node:http.
node:http is the foundation frameworks build on. createServer receives a handler for every request: req contains method, URL and headers, while res sets status, headers and closes the response with end. A server stays alive until closed.
Client request
HTTP server handler
Business logic
Status + headers + body
const http = require("node:http")
const server = http.createServer((req, res) => {
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" })
res.end("hello node")
})
server.listen(0, async () => {
const port = server.address().port
const response = await fetch("http://127.0.0.1:" + port + "/")
console.log(response.status, await response.text())
server.close()
})listen(0) lets the OS choose an available port, which is ideal in tests. Production usually reads process.env.PORT. Every path must end the response exactly once; real services also handle client disconnects and timeouts.
Quick question
What closes and completes a response?
Exercise
Create a server returning SeaCode API, fetch it, print 200 SeaCode API, then close it.
Expected output: 200 SeaCode API
const http = require("node:http")
const server = http.createServer((req, res) => {
})
server.listen(0, async () => {
const response = await fetch("http://127.0.0.1:" + server.address().port)
console.log(response.status, await response.text())
server.close()
})Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.