DEV Community

Khushi
Khushi

Posted on

Server in Node JS

A server listens to the incoming requests from a browser. Then it decides what will be its response to the client, in most cases, it is an HTML page, but it could be an image or CSS as well. How does a server identify what response should be sent?

IP Address

IP addresses are uniquely identified addresses to the computers which are connected to the internet. Some special computers known as Host means they host websites on the internet and publish a website. It will be hosted on the computer somewhere and all IP addresses to identify it and connect to it. They are a series of numbers, they could be hard to remember so we have a domain name to mask these IP addresses. When we type the domain in the browser and it will find the IP address associated with it and it will use that to find the computer that hosts the website, this way it can send requests and get back responses to and from it.

browser → Look-up IP address associated with the domain → Host

when we type something into the browser and hit enter that is a GET request. It s made every time we go to a different web page either by link or directly typing into the address bar.

Now this communication between the client and server happens via HTTPS (Hyper Text Transfer Protocol).

Local host

Localhost is like a domain name on the web but it takes us to a very specific IP address known as loopback IP address. That is 127.0.0.1 and it points to our own computer. We consider our computer as a host when we are developing the website.

Port Number

Port numbers are like a ‘door’ into a computer. It represents a gateway on our computer where a certain bit of software and server should communicate. There is software that interacts with the internet to receive and send data, but all of them has a different port number.

Creating a server

In Node , server are manually created which lives on the backend of our website.

Let s create a server that listens to the request and response to it.

const http = require('http')
const server = http.createServer((req,res)=>{
  console.log('request made');
})

server.listen(3000, 'localhost' , () =>{
    console.log(`listening for request at 3000`)
})
Enter fullscreen mode Exit fullscreen mode

we use the http module to create a server. createServer method takes a callback with two arguments i.e. req(request) and res(response). Once we create a server, it listens to the requests, listen() method takes three arguments (port number, localhost, callback).

here it is! 🙂

Top comments (0)