Build A Basic Web Server with Node.js

Nethmi Jayaweera
4 min readApr 13, 2021

Here we going to talk about how to create a basic web server with node. You may want to fetch something down to your web page ,for that you need to build something that’s going to respond a http request and send something back. That’s what this is!

First of all we are going to create a variable called http this is going to bring a denote package called http.(node has this built in library called http which bringing in to use on the page)

This is really the crust of everything. This is what going to build a webserver.

Let’s have something that is running on the computer that is listening for a request. To do that create a server as shown .

Once you have the server, we can give a listen command. In the listen command we can insert the port number that server needs to listen. And a callback function that needs to fulfill after listening to the given port number.

now you have a basic structure of a web server as shown below!

Now let’s add the remaining. createServer command need to have a function. You can give any name for the function . I use an anonymous function as it going to be use only for one time call. And it is going to give two things out from the server command. So we need to add req and res objects for that function. When a web page makes a request towards the server, the query stream, the method, the body and all the stuff will going to be inside this req object(request). And the res object(respond) will be contain the things we going to be send back.

In here , I’m going to deal only with the response and not going to worry about what will be the request. And just trying to make sure my client side API is working! I set the content type to json and set allow the request to be come from any browser from any daemon. We can use setHeader command any time we want. and then I use writeHead command to set the status as ok. This command can be use once and as a last step.

The very last command must be the end command. It indicates that all is done and from that command we can send the data as well . For that it is needed to add a data object which will contain the data that we are going to send and then after assign it as a string. Now we have done whole process.

Now type node filename.js in the terminal(node) .And it will display our console.log command as shown below.

Next, open a browser and type http://localhost/1234/ and that is the place that I am sending the request to. And I can see the response as shown here.

When you inspect the page you can see the status ok and preview of data as well.

So now we have just create a very basic web server with node .js. Hope this will helpful for you!

--

--