So Express Routers are a good way of keeping things more organized compared to defining all of this logic in the main script that is called to start the project. After all when working on something that does become a little complicated I can end up with a lot of code when it comes to defining these paths. This is often the case when defining a path that will handle post requests where sanitation is of concern.
Express Routers will come into play if I do get into making my own middleware, however even when it comes to making my own express app from the ground a routes folder is a common folder that will compose most compose an express.js root structure along with things like a view folder.
A common task in full stack development involving express.js is that for whatever the reason you might want to do something involving all traffic coming through to an app. Say you want to preform some kind of sanitation, or check of some kind, or to keep things simple maybe you just want to log to the console where reach request is going.
So in the routes path I started off with an all.js file like this:
This could be used with app.use in the main script before any others, it will just simple log the url of the request an continue on to whats next. In a more advanced example that could be used for anything that you would want to do for all the traffic coming into the site. Something similar to this could also be made to be used at the end of a project to catch any traffic that has not went to any known path.
Another file that could be made in the routes folder could make use of simple static paths. In my demo I made a file called static.js that just used some ejs templates to show a simple message.
Regular expressions can also be used to target any path that can match a given regular expression pattern. For this demo I made a file called patt.js that will match any path pattern that begins with “user_” and then any combination of alphanumeric characters.
So in my typical app.js file that will be at the root namespace of the app I will make use of my route files with app.use. The order in which they are added is important, whatever you want used first should be added first, so in this example I would want to start with the all.js file.
Routers in Express are something that I will be using often when making express.js projects. I wanted this to just be a basic post on this subject, but I did not get into something more advanced like making your own middleware, or some kind of actual useful project rather than just a simple demo.