To read more articles in this series please visit myMaking a blog, sample code please visithere.
Create routing
In the previous example, we always used an if else statement to determine the interface path of the request and act accordingly.
This will greatly reduce the development efficiency, and not conducive to the later code maintenance.
Therefore, in common development, routing is used to operate on different interfaces.
Now let’s implement a simple route ourselves:
Code example: /lesson27/lib/router.js
1. Create a Router object to store the routing table. There are two properties, namely GET and POST, which are used to store the callback method of the corresponding GET and POST request address.
// Create a routing tableletRouter = {// Store the route to get request get: {}, // store the route to POST request post: {}}Copy the code
2. Create a method addRouter to add the route configuration, with method as the request method, URL as the request address, and callback as the callback function to process the request.
Method is the request method, URL is the request address, and callback is the callback function to process the requestfunctionAddRouter (method, url, callback) {// To facilitate processing, Method = method.tolowerCase () url = url.tolowerCase () Router [method][url] = callback}Copy the code
3. Create a findRouter method to find the callback function of the corresponding route. The method argument is the request method, the URL is the request address, and the callback function that handles the route is returned.
Method is the request method, url is the request address, and returns the callback function that handles the routefunctionFindRouter (method, url) {// For processing convenience, Method = method.tolowerCase () url = url.tolowerCase () Does not exist, it returns null by default const callback = router. [method] [url] | | null / / callback function returnsreturn callback
}
Copy the code
4. Export the route configuration as a module
Module.exports = {addRouter, findRouter} export module.exports = {addRouter, findRouter}Copy the code