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 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, () => {
  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 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')





Download this site as a PDF / ePub / Mobi ebook, and receive book updates when I publish a new release!