Fetching data from node backend in MEAN stack
In our previous section, we improved our server.js file. We added some error handling code and used the nodemon package for monitoring the node in our project. In this section, we will learn how to get posts. We will go to our node backend for fetching our posts, i.e., dummy posts, because we don't have a database.
We will add all the other codes to our express app because this is a tool that we want to use to create routes that make it so much easier. We will use the following steps to fetch posts:
1) In the first step, we have to register a path because we can fetch posts when we send a get request to that path. For this purpose, we need to get rid of the redundant middleware which we have created before.
2) We will use the middleware in our use() function. So, we will add another argument here. We can add as many arguments in it. Previously, we added a function as an argument that handles the request. Now, we will pass a path for which we want to filter-down, as an argument.
If we add /post, it means only requests targeting localhost 3000/posts will reach this middleware, and all other requests will go into the void because we have no default error handler right now. We name the path /api/posts to make it clear that it is a rest API.
4) We will also introduce an ID because if we had fetched these posts from a database, they would have an ID.
Note: The backend code and the structure of our data are totally decoupled from the front-end model.
We might store some extra information that we don't want to pass on to the client on the backend. We will not define the post as a model in the posts array because we are not using typescript here. We define the posts like this:
5) Now, we need to return them with our response. We can simply pass the object array to the function like this:
Now, we save it and go to the localhost:3000/api/posts, we will be able to see our JSON data.
We can also send back more complex object where we may have a message property that holds the message and then our posts property, which holds the posts array like this:
In the above code, we have added another method status and passed the value 200 as an argument for success.
Now, we save it and go to the localhost:3000/api/posts, we will be able to see our JSON data with the message and posts property like as:
In the next section, we will learn how we can use the angular HTTP client in our application.