Friday, 19 October 2018

node.js: http.createServer([options][, requestListener]): Building Hello World web application

http.createServer([options][, requestListener])
This method returns a new instance of http.Server.

Below table summarizes the arguments of createServer method.
Argument
Type
Description
options
Object
Below table summarizes different options supported by this method.
Option
Type
Description
IncomingMessage
http.IncomingMessage
Specifies the IncomingMessage class to be used. Default value is IncomingMessage.
ServerResponse
http.ServerResponse
Specifies the ServerResponse class to be used. Default: value is ServerResponse.
requestListener
Function
This function is called on every request.

Find the below working application.

HelloWorld.js
var http = require('http');

var server = http.createServer((request, response) => {
    response.writeHead(200, {
        'Content-Type': 'text/html'
    });

    var dataToWrite = '<html><head><title>Hello World</title></head><body>' +
        '<h1>Hello World, Welcome to node.js programming</h1>' +
        '</body></html>';

    response.end(dataToWrite);
});

server.listen(9000);

console.log('Server started and listening on port 9000');


Open browser and hit the url ‘http://localhost:9000/’, you can see below kind of screen.





Previous                                                 Next                                                 Home

No comments:

Post a Comment