In this article, we will understand the concepts related to the server and build our first server using the HTTP module in Node.js
How does the web Work?
When a user browses something on the browser or searches anything in the search box a request is sent to the server. For example, if somebody searches for www.facebook.com a request is sent to the Facebook server asking for the resources, and the Facebook server responds to the request by sending back a response.
Now What does a response is actually?
A response is a kind of answer given to the client who sent a request to the server. A response generally consists of an HTML file. In this case, the Facebook server will return the necessary files. Once the client gets these files, he interacts with them and sends another request to the server, and the process continues.
How do requests and response work?
Now earlier we learned about the basics of requests and responses about how they are triggered and managed by the server. But it is under the hood using a protocol for doing all these things and the protocol is attached to the searches we do in the browser.
For example: When we write Facebook in the search bar and hit enter it adds the http/https protocol to the request.
Now what does an HTTP request consists of?
Request object comprises many properties, but important ones are
Request Line (method): GET, POST, PUT, DELETE, etc.
Request Header: Metadata sent by your browser like browser name, cookies, authentication information, etc.
Request Body: This is used in POST and another request to send data to the server.
What does a Response consist of?
Response object comprises many properties, but important ones are:
Status Line: It states the type of response we received from the server
Headers: Metadata sent by your server back to the client like server name, content size, last updated time, etc.
Body: Actual data to be sent to the client: HTML and CSS, JS, JSON, Image, etc
More about Server and HTTP
HTTP requests and responses can be tracked from Network Tab inside the Dev Tools
We can use the HTTP module present in the node to host our server however developer prefers using a framework like express.js which makes developing a server much easier.
In simple terms, a Server is a function that receives a request processes it, and returns a response. The important thing to note here is a request can only have a single response if there is more than 1 response that you want to send you will encounter an error "Headers already sent"
Functions of a Server
Static file hosting: Sending normal HTML and CSS files as a response. Here HTML and CSS are taken as standard however a server can send any type of data like JSON.
Server Side Rendering: Mixing data with templates and rendering dynamic pages.
Web Apis: Sending data via some APIs or endpoints.