Express.js And MongoDB REST API Tutorial

Setting up the front end

Plenty of tutorials provide a lot more detail on how to query a public API and manage responses from a client request. Understanding the basics of React applications is out of the scope of this article, but you can see examples of how to access the API you just created in the /app/src folder.

In the /app/src/pages/Home.js file, we retrieve the latest three entries from the blog. This is done through a request to the /posts/latest route of the server. In this application, we are using the browser’s native fetch object.

const loadPosts = async () => {
  let results = await fetch(`${baseUrl}/posts/latest`).then(resp => resp.json());
  setPosts(results);
}

This loadPosts function uses fetch and passes the URL to the API. We could use the response in several data formats, but we are explicitly converting it to JSON, as it’s the easiest way to manipulate data in JavaScript. The setPosts function updates the application’s state and forces the user interface to re-render.

All requests to read from the API follow the same pattern. We use the following to fetch all the articles in the app/src/pages/Archive.js page.

let results = await fetch(`${baseUrl}/posts/`).then(resp => resp.json());

The only difference here is the route. The same goes for fetching a single document in app/src/pages/Post.js.

let results = await fetch(`${baseUrl}/posts/${params.id}`).then(resp => resp.json());

We still use the fetch object to create a new entry, but you will need to specify the HTTP method, an additional http header, and the request body. The code to create, update, or delete entries can be found in /app/src/pages/Create.js.

await fetch(`${baseUrl}/posts`, {
  method: "POST",
  headers: {
    "content-type": "application/json"
  },
  body: JSON.stringify({
    author, title, tags: tags.split(","), body
  })
}).then(resp => resp.json());

Doing an update follows the same patterns but with a different method.

await fetch(`${baseUrl}/posts/comment/${params.id}`, {
  method: "PATCH",
  headers: {
    "content-type": "application/json"
  },
  body: JSON.stringify({
    author, body
  })
});

And the same is true for a delete request.

await fetch(`${baseUrl}/posts/${params.id}`, {
  method: "DELETE"
});

If you want to test the application, open a new terminal and run the following.

cd ../app
npm install
npm start