Creating Our Web Server In NodeJS
In this tutorial, we will create our first node js server, Excited right?
To make servers we use a Node JS package HTTP so let’s first import it:
const http = require("http");You must have a strong knowledge of how websites work before creating the server.
Two things are going on:
- The user sends a request to the server
- The server responds to the user
const server = http.createServer((req,res)=>{
res.end("hello this is my response");
})We have created a call-back function here, “req” stands for request, and “res” stands for response.
When I will request the server, in return it will give me a response which will be “hello this is my response”.
Now how will the server know that it needs to listen to the user requests, so we will add another code below:
server.listen(8000,()=>{
console.log("listening to the port");
})We have created a call-back function.
Get Aayan Ali’s stories in your inbox
Join Medium for free to get updates from this writer.
Now we ordered the server to listen at port number 8000, there are many ports you can use any number.
Congrats you are done with creating a server in NodeJS, below is the complete code:
const http = require("http");
const server = http.createServer((req,res)=>{
res.end("hello this is my response");
})
server.listen(8000,()=>{
console.log("listening to the port");
})Let's test it:
Write nodemon index.js or whatever your file name is in your terminal and run it.
Go to your browser and type:
localhost:8000 (If you have made any other port, change this number accordingly)
Click Enter and you will see this:
In your terminal you will get this line:
“listening to the port” because you have printed this line in your “server.listen”.
I hope you understood how to create your own server.
Clap and follow me for more tutorials like this.











