The goal of this assignment is to connect the two components we’ve built and make actions taken in the frontend reflect into actions in the backend.
If you completed the previous assignment on backend development in Express/Node.js and also the last React assignment, your code is ready for this current assignment. The instructions assume you have both frontend and backend code from previous assignments ready but not talking to each other. We’ll work on connecting them. If you don’t have your code ready from previous assignments, talk to me so I can help you to catch up.
At the time you’ll be doing this assignment, our grader will be working on grading the previous assignment looking at your backend branch. Therefore, you should do one of the following:
- make another branch off of
backendfor this exercise, or - merge your
backendbranch back intomainand do this exercise onmain.
1 - Adding our first HTTP request to our frontend
We’ve coded up endpoints in the backend to respond to HTTP requests like GET /users. But so far, we’ve relied on browser’s URL input, the curl command, or a browser plugin to send those requests. To get our frontend and backend working together, we need to use Javascript to generate requests programmatically, dispatch them to the backend, and, if the request succeeds, to act on the response.
First we want to load the list of characters based on the list of users sent from the backend. Recall that our app starts off with no characters being displayed. To request the current list from the backend, we’ll create an internal function called `fetchUsers' which will ll make the GET request through our API on our backend. This function will return the data (the list of users from the backend) which we’ll use to populate our table of characters on the frontend.
// src/MyApp.js (a new inner function inside MyApp())
function fetchUsers() {
const promise = fetch("http://localhost:8000/users");
return promise;
}
Note that this function does not return the data immediately—it instead returns a Promise. Promises are useful when we need to perform an operation which will take some time to finish, or may never finish. We don’t want our code to wait for the data to come back to the server, because that would make our app seem unresponsive to the user. Promises are the basis of asynchronous processing in Javascript. (You may also be familiar with async and await, which are built on top of promises; if you know how to use them, feel free to do so here.)
It is possible to create a Promise (see more explanation here), but in this case, the promise was generated by fetch(), which is built in to Javascript in the browser. The fetch function makes a request to the URL which is given as a parameter. But instead of waiting for the response, it returns immediately with a promise. This promise will be fulfilled when the response is received back from the server.
Now, we need to make our MyApp component call fetchUser function the first time the component is rendered, to start the process of requesting the data. To do that, we’ll use another type of React Hook called Effect. We’ll add useEffect to our import from React in MyApp.js as follows:
import React, { useState, useEffect } from "react";
Now, we’ll define a useEffect hook inside our MyApp functional component to call fetchUsers. We will also indicate, using .then() that when the promise returned by fetchUsers is fulfilled—i.e., the data are available—we want to set the component state using setCharacters:
// src/MyApp.js (a new block inside MyApp())
useEffect(() => {
fetchUsers()
.then((res) => res.json())
.then((json) => setCharacters(json["users_list"]))
.catch((error) => {
console.log(error);
});
}, []);
Since the promise is only fulfilled if the request was successful, the .then clause does not need to check the response status itself. Also notice that since we expect the response to be in JSON format, we call res.json() to parse that into a Javascript object. This process itself is also susceptible to errors, since the JSON returned by the server may be invalid. The parsing occurs asynchronously—res.json() itself returns a promise, which is only fulfilled when the data is successfully decoded. In that case, we can finally call setCharacters to initialize the state of the component with the data sent by the server. Any error in resolving any of these promises will result in the .catch() function being invoked.
Effects can be invoked in response to various events in the lifecycle of a component. We want our Effect hook to be called only when the MyApp component first mounts, because this is when we use the fetched data to build the table for the first time. After that, changes on the table should be handled by adding or removing characters from the state and not fetching all the data again. We indicated that our useEffect hook should be called only when the MyApp component first mounts by passing an empty array [] as the second argument to useEffect. Read more info on the Effect Hooks in the React documentation
2 - CORS (Cross-Origin Resource Sharing)
You can test your code at this point. Remember to get the backend running first since our frontend will try to build the table based on an API call at the time the component will be first loaded. To see what’s happening, you can watch the HTTP requests in the Network tab of Developer Tools.
However, right now, it won’t probably work, even if all your code is correct. The reason is the Cross-Origin Resource Sharing policy. For security reasons, browsers restrict cross-origin HTTP requests—for resources on a different server than that which served the page—initiated from scripts. This means that a web application calling APIs can only request resources from the same origin the application was loaded from, unless the response from other origins includes the right CORS headers.
At this point, if you inspect the page on your browser you’ll see this error ‘No Access-Control-Allow-Origin’ header is present on the requested resource.
To solve this issue, we can either define rules to allow cross-origin requests in specific routes or simply open our backend routes to requests coming from anywhere. The latter is not a good security practice especially for open APIs—routes that don’t require user authentication—but this is what we’ll do for now since we’re using it in a development environment only (not in production).
Now, in our backend project folder, we’ll install an Express library called cors by running the following command:
npm install cors
You can import this library,
// backend.js
import cors from "cors";
and then enable all CORS requests is this one line of code:
app.use(cors());
This goes right before the app.use(express.json()); line.
This will allow our backend to respond to calls coming from a different origin. Note that, even running both of your frontend and backend in your computer, they’re running in different ports, so they’re considered to be in ‘different origins.’
After that, make sure your backend restarts with the changes you made.
Having the backend properly running, you can run your frontend (npm start in your React folder) and see the table component populated with the JSON object sent by the backend as a response to the API call.
Congratulations, your frontend now is able to ‘talk’ to your backend! Don’t forget to commit and push your code to Github.
3 - The submit button and POST calls to add users
In this step, we’ll make POST Request calls to add a new user to the backend, in addition to showing the new user in the frontend table. We need to be a little careful here to make sure the data on the server and in our app stay in sync. We should only add the new person to our local data after we successfully created the new user on the server. Promises are perfect for this sort of situation—where we are uncertain what to do until some other process is successful.
Similar to our fetchUsers function, we’ll now create a postUser function to make the POST request and return the response. We will again use the fetch function,
// src/MyApp.js (a new inner function inside MyApp())
function postUser(person) {
const promise = fetch("Http://localhost:8000/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(person),
});
return promise;
}
In this function, note that we’re calling fetch with the same route, but passing some additional options: method to make it a POST instead of the default GET, body to put the person data into the body of the request, and a Content-Type header to tell the server that the body contains a JSON-formatted object. We also use the Javascript built-in JSON.stringify to convert, or serialize, the in-memory object to a string which we can send “over the wire”. Like with the GET request, we don’t wait for our POST to come back, but return a promise which will be fulfilled when it does.
And we’ll change the updateList() function of MyApp component to use the postUser function:
// src/MyApp.js (a new inner function inside MyApp())
function updateList(person) {
postUser(person)
.then(() => setCharacters([...characters, person]))
.catch((error) => {
console.log(error);
});
}
Remember that we had used this function (updateList) to update the table by changing the app state, adding a new person to the list of characters? Now we’re doing something similar, except that we’ll only update the table if our POST call is successful. In our simple logic, it’s considered successful if the promise returned by postUser throw any error. If there’s an error, we don’t update the state, and consequently no changes in the table. We’re now depending on the backend to effectively change our state by adding a new person to the list and trigger an update on the table component.
To test it, make sure your backend is running then add a character using the front end and make sure the frontend table and backend user list are updated. To test that the backend state is consistent with the frontend, reload the page in your browser. Once it’s all working, commit and push your code to your GitHub repo.
4 - Evolving the code taking your own steps
Here the items you have to implement and the corresponding points you earn:
Use 201 Content Created
In the backend, implement the 201 HTTP code in response to a successful user insertion in the list. Our current logic returns the default 200 code, but the best practice—according to the HTTP specification—is to return a 201 (Content Created). In the frontend, consider the code 201 rather than 200 as a successful insertion. If the response doesn’t come with a 201 status code, do not update the state on the frontend, so therefore no changes will be made to the table. (1 point)
Generate ID on server
If you noticed, in the backend we use IDs while in the front we don’t. We’re sending the objects without the ID field. They can be successfully inserted in the data structure, but now we want them with the IDs. Let the backend decide what is the right ID to the object. Implement an ID generator function to generate a random ID and assign it to the new object that comes through the API post route. So, before appending a new user to the users_list you will add the ID field with a random ID. With that, the list won’t have objects without unique IDs anymore. Hint: you can use Math.random() to generate random numbers in Javascript. This will be a naive algorithm for generating unique IDs, but it’s enough for the assignment. (2 points)
Return newly created object from POST
Third, in addition to returning the right code 201 (see item 1), you should return the updated representation of the object you inserted. This is also a REST best practice. The updated representation is the user object (as provided in the body of the POST request) with its new ID as generated by the backend (see above). For that, you need to attach the newly added JSON object to the response object. Use res.send(newUser) to send a response back to the frontend with a json object in the response body.
On the frontend, you should update the state with the right representation of the object that we requested to be inserted (now, it’ll have the id field).
Hint: you can access the JSON data that comes in the body of the response by calling response.json() (this is in the frontend).
(2 points)
DELETE on backend
You may have noticed that the delete button takes effect only in the frontend. In this item, you’ll make HTTP DELETE calls to delete users in the backend through the API. The DELETE route in the backend should be good based on the previous assignment. If you didn’t do it previously, you have to pause here and implement the DELETE by ID endpoint in the backend.
Then, you have to change the logic in the frontend (see our removeOneCharacter() function in MyApp) and call fetch to make the HTTP DELETE request to the right route. You’ll need to use the {method: 'DELETE'} option and be sure to append the ID of the object to the route URL. An easy way to build the URL string is to use Javascript template literals with string interpolation.
Deleting from the frontend table was already implemented in last week’s assignment, but now you can wait until the promise is fulfilled—which indicates the delete operation was successful on the backend—before deleting from the frontend. Consider using the HTTP status code 204 to represent the successful delete request and no content returned in the response, and the 404 code to represent ‘resource not found’ (so no object was deleted). (4 points)
Show ID in table
Finally, implement an ID column in the frontend. So far, we’ve shown only the name and job fields in the frontend table component. Add the ID column in the table component to show the characters’ ID in the page. Hint: remember the table component is composed of two children components (table header and table body functional components) (1 point)
As you work through these enhancements, be sure to commit and push your code after finishing each one.
5 - Turn it in
Using version control systems is part of every software developer’s workflow. You will turn in one URL pointing to your monorepo. Please, make sure the repository URL is referencing the branch you created at the beginning of this assignment, and where you committed this work.
It’s not a big deal if you get lost in between these assignment steps. If you’re confident you reviewed carefully all the steps and did everything right, use the group chat, email, lab time or come to office hours. If you’re stuck in any step and need help, feel free to reach out.