Build an HTTP Server
How to build an HTTP server with Node.js
Here is the HTTP web server we used as the Node Hello World application in the Node.js introduction
const http = require('http')
const hostname = 'localhost'
const port = 3000
const server = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello World\n')
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
Let’s analyze it briefly. We include the http
module.
We use the module to create an HTTP server.
The server is set to listen on the specified hostname, localhost
, on port 3000
. When the server is ready, the listen
callback function is called.
The callback function we pass is the one that’s going to be executed upon every request that comes in. Whenever a new request is received, the request
event is called, providing two objects: a request (an http.IncomingMessage
object) and a response (an http.ServerResponse
object).
request
provides the request details. Through it, we access the request headers and request data.
response
is used to populate the data we’re going to return to the client.
In this case with
res.statusCode = 200
we set the statusCode property to 200, to indicate a successful response.
We also set the Content-Type header:
res.setHeader('Content-Type', 'text/plain')
and we end close the response, adding the content as an argument to end()
:
res.end('Hello World\n')
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025