Skip to content

Build an HTTP Server

New Course Coming Soon:

Get Really Good at Git

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')
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Node.js Handbook
→ Read my Node.js Tutorial on The Valley of Code

Here is how can I help you: