Node js First Web Server Application

Follow these steps to create Node.js web server application-

1. For creating web server in Node.js, first we need an http module. We can load any module using require() method.

Here, we have included the http module using require() method.


var http = require('http');

2. Create Server - The Http server is created by using createServer() method.

The createServer() method takes callback function. This function takes two arguments request and response. This is called on every page request. The request argument contains client request and the response argument is used to return data back to the client. The listen() method is used to bind the server with a port.


var http = require('http');
http.createServer(function(request, response){
    
}).listen(8080);

3. Now, we will set the content header and send response to the client server.

var http = require('http');
http.createServer(function(request, response){
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end("Good Morning");
}).listen(8080);
console.log("Server is running at http://localhost:8080");

4. First save this file as main.js, open cmd and run this file as -

node main.js

After that, open a browser and type https://localhost:8080

run nodejs on web

Read more articles


General Knowledge



Learn Popular Language