Sunday 13 October 2019

How to create http server in NodeJS?

How to create http server in NodeJS?

Question: How to create a New server in nodejs?

var http = require("http");
http.createServer(function(request, response) {    
response.writeHead(200, {'Content-Type': 'text/html'});    
response.write("<html>");
response.write("<head>");
response.write("<title>Hello World Page</title>");
response.write("</head>");
response.write("<body>");
response.write("Hello World!");
response.write("</body>");
response.write("</html>");
    response.end();
}).listen(8081);



Question: How to Execute above response in browser?
http://127.0.0.1:8081/
You should be already installed WampServer/Xampp Server.


Question: How to install httpdispatcher?
npm install httpdispatcher



Question: Give an example of http GET Request?

dispatcher.onGet("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
Contact US Page</h3>
');
});



Question: Give an example of http POST Request?

dispatcher.onPOST("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('<h3>
Received POST Data</h3>
');
});



Question: Give an full example of httpdispatcher which have multiple pages?

var dispatcher = require('httpdispatcher'); 
function handleRequest(request, response) {
    try {
        //log the request on console
        console.log(request.url);
        //Disptach
        dispatcher.dispatch(request, response);
    } catch (err) {
        console.log(err);
    }
}
dispatcher.setStatic('resources');

//A sample GET request    
dispatcher.onGet("/contactus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
Contact US Page</h3>
');
});

dispatcher.onGet("/aboutus", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h3>
About US Page</h3>
');
});


var http = require('http');
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(8081, function() {
    //Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", 8081);
});