DEV Community

loading...

Build an HTTP Server

flavio ⚡️🔥
I write tutorials for developers at https://flaviocopes.com
Originally published at flaviocopes.com on ・1 min read

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}/`)
})
Enter fullscreen mode Exit fullscreen mode

Let's analyze it briefly. We includes 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
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

and we end close the response, adding the content as an argument to end():

res.end('Hello World\n')
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app