In the previous chapter, we discussed how to create REST APIs using Express.js. You may have noticed that we only briefly covered how to implement the APIs without discussing how to call them in the frontend. That was, in fact, by design. Micromanaging all the details using plain JavaScript would have been too overwhelming.
However, now that we've covered React.js, our first frontend JavaScript framework, we can revisit this topic, and this time, we are going to create a fully functional blog application.
Designing the application structure
As usual, you should have a big picture of the entire project. The project will be divided into two applications, a frontend app and a backend app.
The backend part should be handling the database connections and interactions, such as searching, adding, modifying, and deleting records based on different requests. And, of course, it should have the routes and controllers to handle these requests. For our blog app, it should be able to process the following requests:
GET /posts
: Lists all posts.POST /posts
: Creates a new post.GET /posts/:id
: Retrieves a specific post by ID.PUT /posts/:id
: Updates a specific post by ID.DELETE /posts/:id
: Deletes a specific post by ID.
This is very similar to the blog app we created before using Express.js, only this time, we don't need the view layer to display the user interface, that is the job for the frontend. And instead of rendering the page using the render()
method, your backend app should respond with a proper structured format such as JSON.
As for the frontend app, it replaces the role of the old view layer, and as an independent app, it offers greater flexibility and more advanced features. It should fetch/post data via the APIs we discussed above, and use that data to display the corresponding webpages. For our blog app, there should be 4 pages:
- Home page: Displays a list of posts.
- Create page: Displays a form used to create a new post.
- Update page: Displays a form used to modify an existing post and a delete button to delete that post.
- Post page: Displays the title and content of a post.