Jun's Coding Journey·2022년 11월 1일

[Challenge] Youtube Clone

목록 보기

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 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

Importing and Exporting

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.

Using Routers

// 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)

Example of Clean Code for Routers





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

Greatness From Small Beginnings

0개의 댓글