Node.js HTTP Module

Node.js HTTP Module

Creating our first web-server using Node.js HTTP Module

Node.js has one built-in module i.e. Node.js HTTP Module. This module allows us to transfer data over Hyper-Text Transfer Protocol(HTTP). With this module, we can create a HTTP web-server which listens to some port, takes request, processes it & responds back to client.

Enough talk. Let's go for action. Let's create a file with server.js name. Since Node.js HTTP Module is a built-in module so we don't need to install it into our computer. Only thing we have to do is to incorporate it in our server.js file such as

const http = require('http');

Now create server using createServer() method which listens to port 8000 and responds to client with "Hello world!" after processing the client's request

const server = http.createServer((req, res) => {

    res.write('<h1>Hello world!</h1>');
    res.end();

}).listen(8000, () => console.log('server started and tyned at port 8000'));

Now run this server.js file by executing following command in terminal

$ node server.js

our server has been started and tuned at port 8000

Screenshot (67).png

Now launch the browser and go to URL localhost:8000 This sends the request to our server, server takes the request, processes it and responds back to us by "Hello world!" message.

Screenshot (69).png

That's all. Happy learning!