17. Routing & Request handler

In part 16:- creating a server we have created “devTinder“ folder now starting from there in the same folder.
1 const express = require("express"); 2 const app = express(); 3 const port = 3000; 4 app.use("/", (req, res) => { 5 res.send("test"); 6 console.log("test"); 7 }); 8 app.listen(port, () => { 9 console.log(`Listenin on port ${port}`); 10 });
In app.js above code is written
line 4-7 is not considered a direct request handler, but it is a middleware which allows to execute code before reaching the actual request handler for a specific route, essentially it is function that run on every incoming request to your application. In browser when we enter URL ““http://localhost:3000/” we can directly see “test“ on screen and after “/“ anything which is entered like this “/test“ or ”/test/test/test” will give same output on screen.
Position of middleware and request handler matters while creating a server
for example
const express = require("express"); const app = express(); const port = 3000; app.use("/", (req, res) => { // req handler 1 res.send("test"); console.log("test"); }); app.use("/test", (req, res) => { //req handler 2 res.send("hello from test1"); console.log("hello from test1"); }); app.use("/hello", (req, res) => { // req handler 3 res.send("hello from test2 "); console.log("hello from test2"); }); app.listen(port, () => { console.log(`Listenin on port ${port}`); });
when req handler 1 is accessed in browser it will give test but as soon as “/test“ or “/hello“ is entered at all route output will be same no matter what these route are consoling in their body, because “/“ as req handler 1 is first written it will be parsed from top to bottom and all route “test“ or “/hello“ we will get same output “test“ but as soon as position of handler are changes like req handler 3 is at top than req handler 2 than req handler 1, then at different route like at “/test“ we will get “hello from test1“ and at “/hello“ we will get “hello from test2“ also at “/“ we get "test“.
HTTP methods
http methods are used to request and modify data on the server there are different type of http methods like get, put, post, delete etc.
using http methods we will create request handler to perform different functionalities like sending data to server, getting data, deleting data etc.
for example:- just random routes to know how they look like
GET/profile :- to get data from “../profile“ route
POST/sendRequest:- to send request to backend at “…/sendRequest“ route etc.
One thing to note that it is not good way to test different routes API (the thing which we are writing in tab of browser) in browser and it is also quite difficult for large project having number of request handler so here we will use a software known as postman to create and test API routes.
From now onwards we will test our routes API in postman, we must keep these http methods in our mind while working with request handler.
POST:- method to submit an entity in specified resource.
GET:- method to get an entity from specified resource.
DELETE:- method to delete a specified resource.
PATCH:- method for partial modification of resource
//in app.js const express = require("express"); const app = express(); const port = 3000; app.use("/", (req, res) => { //middleware res.send("hello from middleware"); console.log("hello from middleware"); }); app.get("/user", (req, res) => { // /get req handler res.send("hello from /GET user"); console.log("hello from /GET user"); }); app.post("/user", (req, res) => { // /post req handler res.send("hello from /POST user"); console.log("hello from /POST user"); }); app.listen(port, () => { console.log(`Listenin on port ${port}`); });
when we test different route in postman like “ GET …/user“ or “POST ../user“ at all route we will get same output of middleware body for same above reason which we have mentioned that order of route matter while writing code.
at “GET ../user“ in postman we will get “hello from /GET user“ in body
but also at route like “GET …/user/xyz“ or “GET …/user/2/3“ we will get same output.
Now lets see some different combination of dummy routes which are used to send route request in different forms.
Case 1:- “GET ../ab?c“
Description:- here it means that “b“ character is optional in “GET ../ab?c“ route it will give same output on different route like “GET …/ab or …/c or …/ac or …/abc“
Case 2:- “GET …/ab+c“
Description:- here a and c at last , act like a regular expression for example at route “GET …/abc or …/abbc” we will get same response means no matter what we write in between a and c all will give same response.
Case 3:- “GET …/ab*cd“
Description:- route must start with “ab“ and end with “cd“ for example “GET …/abFARAZcd or /abcd or abbbbbcd“ at all we will get same response.
Case 4:- “GET …/a(bc)?d“
Description:- here “bc“ is optional for example at route “GET …/abcd“ or “GET …/ab“ we will get same response.
Case 5:-”GET …/a(bc)+d”
Description:- accept routes like “…/abcd“ or “…/abbcbc“
Case 6:- “GET …/a/” more accurately like this
app.get(/a/, (req, res) => { console.log("this is regex type route"); })
Description:- if in path route character ‘a’ lie it will work or example route such as …/a or …/bbabb or ../cab but not …/b
Case 7:- “GET …/.*fly$/“ more accurately
app.get(/.*fly$/,(req,res)=>{
res.send(“hello from route ending with “fly”“)
})
Description:- we will get response for route having fly at end for example:- “…/fly“ or “…/butterfly“ or “…/skyfly“
and many more cases which can be used in various code bases.
Query Params
“params” generally refer to the parameter that are added in the path of the URL, while “query params“ refer to the parameter in the query string. Now lets see in params in code.
1. const express = require("express");
2. const app = express();
3.const port = 3000;
4.app.get("/user/:userId/:id1", (req, res) => {
res.send("hello from /GET user");
console.log(req.params);
});
app.listen(port, () => {
console.log(`Listenin on port ${port}`);
});
at line we can see we have added multiple parameter a “userId“ and “id1“ these are called params to get those in console when we hit URL “http://localhost:3000/user/1/2“ either from postman or browser we get these params in console
Now in query params suppose in browser or in postman we want to enter “userId=100“ , “name= “faraz alam”“, “country= India“ in the route “http://localhost:3000/user“ how to get all this external query string in console.
First of all in browser write this “http://localhost:3000/user?userId=100&name=farazalam&country=India“ then write this code with console log of “req.query”
const express = require("express");
const app = express();
const port = 3000;
app.get("/user", (req, res) => {
res.send("hello from /GET user");
console.log(req.query);
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
when we hit the above URL with query string we get
Subscribe to my newsletter
Read articles from Faraz Alam directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Faraz Alam
Faraz Alam
Assalamualaikum warahmatullah wabarakatuh( traditional Islamic greeting in Arabic "Assalamu alaikum": "Peace be upon you." "Wa rahmatullahi": "And the mercy of Allah." "Wa barakatuh": "And His blessings.") I’m Faraz Alam, and I’m documenting my journey through the world of software technology. Despite earning a master’s degree in Computer Applications and having access to opportunities provided by my tier-3 college, I struggled to take full advantage of them due to poor management and a less productive environment. This led to joblessness, primarily due to a lack of upskilling. Now, I am dedicated to enhancing my skills and knowledge with the aim of securing a valuable job offer from leading product-based companies, including those in the FAANG group (Facebook, Amazon, Apple, Netflix, Google) and other prominent tech giants. This documentation is not for self-promotion; rather, it is for anyone who is waiting for an opportunity but feels they lack the tools and skills required to overcome challenges. It’s a testament to the effort and responsibility needed to navigate the journey towards success when you take charge of your own path. Date: 31 July 2024, 07:25 AM This page will be updated regularly to reflect new achievements and milestones as I continue to build my career.