Create server using http module in Node.js

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 = '127.0.0.1';
const port = 3000;

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

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 http://127.0.0.1:3000/

Open the browser and input url http://127.0.0.1:3000/. 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>');
    res.end();
}).listen(3000);

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.

Tags: