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 Worldn')
})
server.listen(port, () => {
console.log(Server running at http://${hostname}:${port}/)
})

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).

http.IncomingMessage

An http.IncomingMessage object is created by

  • http.Server when listening to the request event
  • http.ClientRequest when listening to the response event

It can be used to access the response:

  • status using its statusCode and statusMessage methods
  • headers using its headers method or rawHeaders
  • HTTP method using its method method
  • HTTP version using the httpVersion method
  • URL using the url method
  • underlying socket using the socket method

The data is accessed using streams, since http.IncomingMessage implements the Readable Stream interface.

http.serverResponse

Created by an http.Server and passed as the second parameter to the request event it fires.

Commonly known and used in code as res:

const server = http.createServer((req, res) => {
  //res is an http.ServerResponse object
})

The method you will always call within the handler is end(), which closes the response, the message is complete and therefore the server can send it to the client. It must be called on each response.These methods are used to interact with HTTP headers:

  • getHeaderNames() get the list of the names of the HTTP headers already set
  • getHeaders() get a copy of the HTTP headers already set
  • setHeader('headername', value) sets an HTTP header value
  • getHeader('headername') gets an HTTP header already set
  • removeHeader('headername') removes an HTTP header already set
  • hasHeader('headername') return true if the response has that header set
  • headersSent() return true if the headers have already been sent to the client

After processing the headers you can send them to the client by calling response.writeHead(), which accepts the statusCode as the first parameter, the optional status message, and the headers object.

To send data to the client in the response body, you use write(). It will send buffered data to the HTTP response stream.

If the headers were not sent yet using response.writeHead(), it will send the headers first, with the status code and message that’s set in the request,which you can edit by setting the statusCode and statusMessage properties values:

response.statusCode = 500
response.statusMessage = 'Internal Server Error'

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 Worldn')

If you like this post, don’t forget to share 🙂

This article is written by our awesome writer
Comments to: How to Build an HTTP server In node.js

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password