Has it ever crossed your mind how the web works, each time you enter a URL into your browser,
to open a new webpage (resources)? or requesting data from some external API?
Our browser
also called the client, send a request to the server where our web pages are hosted and the server will send back a response which will contain the webpage as requested. and this process is called the Request-Response Model
HTTP Request-Response
This allows clients and servers to communicate by sending requests and response messages from client to server and back.
Steps on the Request-Response Cycle
Entering a URL resource link:
Imagine us visiting Google Maps by writing
google.com/maps
into our browser as a URL. And every URL gets an HTTP or HTTPS which is a protocol used for connection.The Domain Name is
google.com
white the resource we are going to access is the/maps
.TC/IP Connections - (Transmission Protocol)
This connection is established between the client and the server. it defines how data are transmitted across the web. The Internet's fundamental control system
HTTP Request
The HTTP is just a protocol that allows clients and servers to communicate by sending request and response messages.
Response
The answer was that after the server had finished handling a request and thus sent back a response to the client.
Express JS
When it comes to building web applications using Node.js
, using Express.js
is an easier way of writing node.js
code.
What is Express:
Express is a minimal node.js framework, with a higher level of abstraction. which means it was built on top of node.js
It contains a very robust set of features like: Complex routing
, easier handling of request and response
, middleware
, server-side rendering
etc
The Express Request-Response Cycle
To understand the essence of Express development, we need to understand the Request-Response cycle.
From the Image Above, the request-response cycle or Express app receives a request when someone enters a URL to hit a server, which then creates a response object
, that data will then be used and processed to generate and send back a meaningful response object
To process this data we use what is called Middleware
Middleware
is called middleware
because it is a function that is executed, in the middle of receiving the request and sending the response. These functions determine the flow of the request-response cycle. They are executed after every incoming request.
The Middleware sits between the request and the response from the server, creating a sort of firewall bridge between them. And can manipulate the request or the response object
in a nutshell, the request-response cycle starts with the incoming request, then executes all the middleware in the middleware stack step by step, and finally sends the response to finish the cycle.
Routes
They are the endpoints defined in our server that help to perform operations for a particular client request.
Even the Express routes are middleware, so we can think of our route handler function we wrote as a middleware function. They are simply middleware functions only executed for certain routes.
Routing and Routing Methods
Routing refers to how a server-side application responds to a client request to a particular endpoint. This endpoint consists of a URI (a path such as /
or /books
) and an HTTP method such as GET, POST, PUT, DELETE, etc.
Routes can be either good old web pages or REST API endpoints. In both cases, the syntax is similar syntax for a route that can be defined as:
app.METHOD(PATH, HANDLER)
const express = require('express');
const app = express();
//routing method
app.get()
//routing path
'/about'
app.get('/about', (req, res) => {
res.send('welcome to the about page')
})
Middleware Functions
Middleware functions are those functions that have access to the request object (req
), the response object (res
), and the next
function in the application’s request-response cycle. The objective of these functions is to modify request and response objects for tasks like parsing request bodies, adding response headers, making other changes to the request-response cycle, ending the request-response cycle, and calling the next middleware function.
The next
function is a function in the Express router that is used to execute the other middleware functions succeeding the current middleware. If a middleware function is included next()
that means the request-response cycle is ended there. The name of the function next()
here is arbitrary and you can name it whatever you like but is important to stick to best practices and try to follow a few conventions, especially if you are working with other developers
what is very important is to keep in mind that the order of middleware in the stack is defined by the order they are defined in the code.
So a middleware that appears first in the code, is executed before one that appears later. And so, the order of code matters in Express.
Now thinking about the whole process like this, our request and response objects that were created in the beginning go through each middleware where they are processed, then at the end of each middleware function, a next function is called called, which is a function that we have access to in each middleware function. So when we call the next function, the next middleware in the stack will be executed with the same request and response object. And this happens with all the middleware until it reaches the last one. And just like this, the initial request and response object go through each middleware step by step. and you can think of this whole process as kind of a pipeline where our data goes through from request to final response.
creating express middleware:
const express = require('express');
const app = express();
// express middleware;
app.use(express.json())
app.get('/home', (req, res) => {
res.send('Home Page');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
app.listen(3000, () => console.log('Example app listening on port 3000!'));
Creating a custom middleware:
const express = require('express');
const app = express();
// Simple request time logger
app.use((req, res, next) => {
console.log("A new request received at " + Date.now());
// This function call tells that more processing is
// required for the current request and is in the next middleware
function/route handler.
next();
});
app.get('/home', (req, res) => {
res.send('Home Page');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
app.listen(3000, () => console.log('Example app listening on port 3000!'));
Conclusion
The request-response cycle is everything we just talked about. it starts with the incoming request, then executes all the middleware in the middleware stack step by step, and finally sends the response to finish the cycle.
This is just a brief overview of how the request-response cycle works and not setting up an entire Express Application.
Thanks for reading...