ADVERTISEMENT
ADVERTISEMENT

Home » Node.js

Building Web Server using Node JS

In this article, we are going to learn to build web server using Node JS, this post contains source code including the outputs.
Submitted by Mansha Lamba, on October 18, 2018

We have been through enough stuff on NODE JS in my previous articles and now we are ready to build a fully functional web server listening to requests on the designated port number.

Code:

var http=require('http');

function myfunc(request,response){
	console.log(" user made a request at "+ request.url );
	response.writeHead(200,{ "Context-Type":"text/plain"});
	response.write("welcome to 4000 ");
	response.end();
}

http.createServer(myfunc).listen(4000);

console.log("server made");

Output screenshot 1

Node JS | Build web server output 1

Output screenshot 2

Node JS | Build web server output 2

Explanation of the code:

For building web server we first need to import http module inbuilt in Node JS which is done in line number 1.

Then in line number 10, createServer method of http is being used to designate a port number for listening requests. Here I have used 4000.

We have passed a function reference i.e. myfunc as an argument in createServer method that means whenever user will go to localhost 4000 via any browser this function will be called.

In line number 3, I have defined function myfunc. It has two parameters request and response that are inbuilt in http module.

The request has info regarding the request made by the user like here I have used request url.

Likewise, Response is used to generate require response or output.

First, we mention the type of response and then the content of the response.

In today’s era web development is in immense demand, thus every Software industry enthusiast ought to have knowledge regarding it.

This article provides an initial step towards web development career.

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.