How To Create a Web Server in Node.js with the HTTP Module

  782 views   1 year ago NodeJS

Node.js has built-in HTTP module to transfer data over http protocol. HTTP module also used to create http server and send response to the specific server port.

To use the HTTP module, use require() method to import module.

const http = require('http');

Now use createServer() method to create HTTP server and listen() method listen to the given port.

Here is the example. Create file http.js and save the below code into it.

const http = require('http');

const hostname = '';
const port = 3000;

const server = http.createServer(function(req, res) {
    res.write('Hello World!\n');

server.listen(port, hostname, function() {
    console.log(`Server running at http://${hostname}:${port}/`);

Now run the file into node from Terminal.

node http.js

You will see below console message into response.

Server running at

Open the browser and input url The server will response the data that we passed in res.write() method.

You can also send response header using res.writeHead() method. The below example will return 'Content-Type': 'text/html' header in response.

const http = require('http');

const server = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<h1>Hello World!</h1>');

In this article, we have learned to create http server and send response data with header. In the next article, we will use other methods of http module.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]