Grouping the Backend Routes in MEAN Stack
In our previous section, updating and fetching post were working well. The authentication was still missing there. Right now, we are organizing everything in the app.js file. This file is still not big, and in this section, we will organize our routes differently because we will later add more routes for authentication. It will be good if we group them. We will use the following steps to group them:
3) We will define our routes, and just as we did it with the app in the js file, we can use router.get() in the following way:
This works in the same way as the app did before. In this, we can replicate the route by grabbing its URL. We pass the URL as a first argument and the function as a second argument. We can also grab all the routes in the app.js file.
4) So, we will cut all the routes from the js files and add them in the posts.js file and we will also replace app with the router in the following way:
5) Now, we need to export this router to make express aware of it, and for this, we will use the module.exports syntax in the following way:
6) We need to import it into our app.js file so that we can again make our main express app aware of these extra routes because if we don't import router, then all our routes would fail. So, we will import the routes in the following way:
After importing the route object, we need to make express aware of it, and that will be done in the following way:
7) There is no use of the postmodel in the app.js file because we used our model in the routes. So, we will remove it from the app.js file and import our postmodel into our posts.js file.
8) We can improve use(postroutes). Later, we will have multiple routes file, and our posts.js file should only handle routes which reach /api.posts/nothing or slash something like id. We cut the /api/posts from our posts request and assume that any route or request to reach that file was already filtered. For that, we will add /api/posts in the app.js file as a first argument of app.use() method in the following way:
By adding this line of code, we filtered for requests going to API posts and only requests where the URL or the URL path starts with /api/posts will be forwarded into the posts routes file and routing setup.
9) Now, we also need to remove /api/posts for the put request, get requests and delete requests.
We should still have a working app as before, and we will test this by adding or deleting the post. So, we will go back to our angular app and try to add and delete a post.
Everything is working well after grouping the routes into a new file. In our next section, we will learn how we can add a loading spinner into our app.
Download Complete Project(Grouping routes.zip)