We know web technology works on the server site and client site. We will not go deep through this fact but we will just see how this simply works with http module in node.js.
In this article, we will know What is HTTP Module?, How can HTTP module be used to create server?. Then let’s start—-
Http Module:
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).
To include the HTTP module, use the require() method:
How can we use node.js as a web server using Http Module:
We can use createServer() method to create the server.
In above code, we imported {createServer} module using require directive to access HTTP module. The function passed into the http.createServer() method, will be executed when someone tries to access the computer on port 8000. The request and response bindings are objects representing the incoming and outgoing data. The first contains information about the request, such as its url property which tells us to what URL the request was made.
So, when one open that page in the browser, it sends a request to his/her own computer. This the causes the created server (In this case, server) to run and send back a response, which can be seen in the browser.
To send something back, response object works. writeHead() method set the server response type. Here, the content will be shown as html page. Multiple header may be use. The actual response method is sent with write() method. The call to server.listen() causes the server to start waiting for connections on port 8000. Finally, the response ends with response.end() method. If we initiate our code as –
We will see this in the browser as expected.
That’s for today. Happy Coding!!!!!
Reference-https://eloquentjavascript.net/20_node.html