A router is a guide that receives a request and directs the request to various handlers within a program. In the browser, a router is a library that decides what webpage is presented by a given URL. In short, router allows you to control controllers and url's in a much easier way.
Routers use methods of the Express app object that correspond to HTTP methods. For example, app.get() to handle GET requests and app.post() to handle POST requests. These routing methods specify a callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application “listens” for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.
Apart from its usage, routers do not necessarily need to be written on the same file as the server. In fact, it is recommended to write clean code by dividing routers and controllers from the server for better structure
When we divide routers and controllers from the server, we are basically creating separate environments where they do not have any effect on each other.
We can, however, import and export files between the server in order to make connections. Using the import and export keywords, we can create object packages that can be sent to the server in order to connect to a specific URL.
// creating a router const router = express.Router();
// applying a router globally app.use("/", router);
// making the router work const handleRouter = (req, res) => res.send("Home"); router.get("/", handleRouter)
A Parameter in URL is able to pass information about a click or a submit made by a user. These parameters are basically variables that are stored in a url through a router.
By applying regular expressions to a router, we can control the type of variable gets displayed on the URL. Without regular expressions, the order of the get requests on code would matter. However, with regular expressions, the order does not matter and express will freely be able to locate all the parameters