Last post, I have learned to develop my first Express App from the course. Basically, it has three routes. When we type "/", "/bye" and "/cat", the app will receive the request and send the matched response to us.
But, if we want to send a nice message when users type other texts after slash, what should we do?
We can write a "*" route which will run whenever out app gets any request to any url aside from those three routes that we have already defined.
app.get("*", function)
In the App.js file, we add a new star route, and it will send you a new message whenever you type any undefined request.
I run my app, and put some random texts after slash, and hit enter. All I get is "You are a star!".
If we move the star route to the top of those three routes, what will happen? The instructor run the app, the result is even though we send the "/", "/bye" or "/cat" request, all we get is "You are a star".
Therefore, the order of route is matters!
If we put the star route at first, nothing else will be matched ever. The key concept is that the first route that matches a given request is the only route that will be run. That's why we normally put the start route at the bottom.
Another thing I learned is route parameters.
Image if we have a blog which covers a lot of subjects, it would be super stress to cover every single subject in app.get. The code will not DRY(don't repeat yourself), and it wastes a lot time. The most importantly, we will never match all subjects that users want to search.
To solve the above problem, we need to use route parameter which we can use to define a pattern in a route that doesn't have to be matched word for word. It just needs to match the same patterns.
For example, I write a route pattern:
app.get ("/a/:subName, function)
The ":subName" is the pattern. Users can type "/a/anyname" to send the request, and receive the relevant message.
When I type "/a/babywipe" in the url to make a request, I will receive the new message.
We can also add more "/:patterns" in the app route too. For example, we can add "/:id/:title/" after the comments.
As the result, when I type the "/a/babywipe/comments/123/best_baby_wipe" which matches the pattern route, the app send "Leave Your Comment Here" message back to me.
Comments
Post a Comment