How to create HTTP server in Node?

To create HTTP server in node, we have to include http module. As shown below:

var http = require(“http”);

// request variable holds all request parameters
// response variable allows you to do anything with response sent to the client.
http.createServer(function (request, response) {
// Attach listener on end event.
// This event is called when client sent all data and is waiting for response.
request.on(“end”, function () {
// Write headers to the response.
// 200 is HTTP status code (this one means success)
// Second parameter holds header fields in object
// We are sending plain text, so Content-Type should be text/plain
response.writeHead(200, {
‘Content-Type': ‘text/plain’
});
// Send data and end response.
response.end(‘Hello HTTP!’);
});
// Listen on the 8080 port.
}).listen(8080);

This code is very simple. You can send more data to the client by using theresponse.write() method, but you have to call it before calling response.end().

Now, save file as server.js and in your console write following:

$node server.js

Open up your browser and navigate to http://localhost:8080. You should see the text “Hello HTTP!” in the page.


ProsperaSoft offers Node.jsĀ development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>