Every website you've ever visited works the same basic way: your browser sends a request to a server, and the server sends back a response. The http module lets Node.js play the server side of that exchange, with no external packages needed.
const http = require('http')
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Hello from Node!')
})
server.listen(3000, () => {
console.log('Server running at http://localhost:3000')
})Run this file with node, then open http://localhost:3000 in a browser. Unlike the scripts you've run so far, this one doesn't finish — server.listen() keeps the program alive, waiting for requests, until you stop it with Ctrl+C.
The function passed to createServer() runs once for every incoming request, and receives two objects:
| Object | What it holds |
|---|---|
req (request) | What the browser asked for — req.url, req.method, req.headers |
res (response) | What you send back — res.writeHead(), res.write(), res.end() |
res.end() is required — the browser keeps waiting until it's called, and the connection never finishes without it.
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Welcome home')
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('About this site')
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.end('Not found')
}
})This if/else chain checking req.url is, at its core, exactly what a web framework's "router" does — just with a much friendlier syntax and a lot more built in. You'll see that properly in the Express lessons later in this course.
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end('<h1>Hello!</h1><p>This is a real webpage.</p>')The Content-Type header tells the browser how to interpret what follows. Set it to text/html and the browser renders the tags; leave it as text/plain and it shows the raw <h1> text instead of rendering it.
The first argument to writeHead() is the status code — a number that tells the browser how the request went. 200 means success; 404 means "not found"; 500 means the server hit an error. Getting these right matters — a page that failed but returns 200 looks successful to search engines and monitoring tools even when it isn't.