Loading
Lesson 14
Courses / Build a Web App like Twitter from Scratch Using HTML, CSS, JavaScript, Express, MySQL
Using Fetch API to Get Data from the Server JSON API Written with Express, Cors middleware

Video Transcript

Hello, we are back. So let's start building a request from the client side so it can get the data from the server. Right now the hard coded data is in the HTML document. We don't want that anymore. We want the client to make a request to get all the entries. The server side will send back all the entries and then we're going to generate entries, boxes dynamically and inject them into the document object model, this page right now, right here. Back to the text editor under index.html, we don't need all these entries anymore. So we'll delete all the entries from the entry list, just skip the div for the entry list there. It's going to be empty. Nothing. Now back to script.js, we're going to add more code so we can make a request to get all the entries from the server side and then generate those boxes with the entry text and then inject that into the DOM. Let's create a new function to do that. The responsibility of this function will be to get, to fetch the entries or get the entry. Make sure to call this function here. Of course we could have the code outside without being a function, but I want to encapsulate the well-defined code responsibility to functions. Ultimately later on, as you get better and better at this, you're going to have a standard of organization for your code and everything will have been modularized into functions with a well-defined concern. In any case, let's... So to make a request to the server, we need a way to make an HTTP request. We can do that using the fetch API. To use that, it's very simple. Just call fetch. Now this fetch function will take, by default, if your verb for the HTTP is get, you just need to call get fetch like so. Pass the argument with the URL of the server side. This is the endpoint. Remember we had done localhost 3000 slash entries. This is what goes here. So HTTP colon slash slash localhost colon port 3000 slash entries. The endpoint. Finally, this is going to give us what's called a promise. Let me show you here in the browser. If you want to try it out, copy the code, go to the browser, go to the console and try it here. You can ignore the error for now, focus on what's given back as the return value of this function call. You see it's a promise object. Now the promise is something that we can use... Let me explain. So when you make a request to the server, it takes some time for you to get a response, right? So you cannot have the code work right away and give you the entries right away. So there's a promise there going to get something back later. Now first upon a promise is pending, right? That's why you got this. Now it's pending because, hey, I contacted the server. I asked for the entries. I'm still waiting for that data to be sent back. Now while you wait, the program cannot stop working. So JavaScript will have continue executing other things. But to handle the promise, to actually do something when you get the response back after that time was elapsed, you either get a reject from the server or you get some an acceptance, right? So the promise can be either fulfilled or rejected. So in this case, my promise was rejected because we got some sort of error. So the server got the request, but something went wrong and he replied with... And we got a reply here in the promise. We got a promise that was rejected. Nevertheless, the promise is already finished, right? We got some sort of response. Now we got to do something about it. Okay, that's the next step. But before that, let's check out this error message. Access to fetch add slash entries from original has been blocked by course, CRS, policy. No access control allowed origin headers present on the request of resource. If an opaque response serves their needs, set the request mode to no course fetch resource course to sale. Okay, I'm not going to get into much detail about this. I'm just going to show you how to get rid of this message so it works locally, okay? But you might want to do your own research. If in the future you end up having to work with this, but usually you don't have to worry about these things when you're developing because this will already have been set up for you and everything. In any case, to fix this problem, I'm going to use the middleware for express. Going back to Adam, go to the server.js file. Here after creating the express app, I'm going to say app.use and I'm going to use course, but this thing is not yet defined. Let me check out the, I think we have to install the package. Let's go to the terminal. Let me kill the server control C. I want to say npm install CRS. This is npm package. Now with that package, I'm going to require that here. So const course, require course. Let me see if it works. I don't know if I have to call it or not. So let me see if it worked without having to call. I'm going to run the server nova server.js. I'm going to test it out, see if it works. I'm going to call fetch here in the console again, expand. Okay, seems like it might have worked. Let me try just see if it's something here. Okay, so I think that I might need the rent is after all. I didn't get any response. So restart the server, do it again. There you go. Now I got back the response. So you have to have the parentheses after all. What I did here is use what's called a middleware. Middleware is a very common thing when you do server side programming with these frameworks, API frameworks serving JSON. A middleware is something that gets in between your handling of the response. For example, the client requested get slash entries. Now normally when you request get slash entries is going to go directly to this function and execute the code to send back the entries. But what if you wanted to do something in between? Before you reach this function, you want to have something in between, which is the cores middleware. And that's in between is what I'm doing in online six. Now you can have this middleware go only in between here this specific route, or you could apply that to every single route that you define in your application here, server side. So that's what I did using the app.use function. This will apply this middleware to every single request that comes in. And it'll be shoved there in between that request and the response that you give. So in this case, setting up something to do with that core, that header that we saw in the error message to allow the client side to receive the data. So that's it for that. Now that going back to script.js, we got our fetch we know now it's working. Now fetch returns a promise promise to something will be returned later. Now until then we to handle that promise you have to use what's called the then function. So you do dot then, meaning after this promise is fulfilled, then do this. And in this case, going to give me back a response object. And you put like a callback function here, response arrow, open braces. Now if you want to take a look at that response, I can do a console log here. Let's do that breakpoint thing that we saw. Let's go back to the browser, I'm going to go to sources, I reload here, click on script.js, put a breakpoint in line 15, right at the console log. Let's reload a page. Now it stopped at the breakpoint, right? Remember the code is right here. It hasn't executed this yet, but let's look at response. So hover over response, you can see there's a lot of stuff here about the response. Now if you look at the prototype, I think there's this function called JSON. And this is the function I used before when I was quickly trying to see if fetch was working. This is what we're going to need. Let me show you why. Going back to the console here, actually not there, I'm going to press escape. So I can get this console running here. I don't like this message. Click console and go here. You can type response to see what's inside that we already saw. Now if I try something like response.json and call this function, what do we get? Well we got a promise back. Now to handle promise what we do need to do. Then after this promise is fulfilled, do something. Now this something I already know is going to return me the entries. So that's why I named the variable like so. But you don't have to name it entries. You could name anything you want. But it makes sense to me to name that parameter entries. Then entries, I'm going to do the console log entries so it shows that prints that to this console. And why didn't they do? Then entries console log. It was like nothing worked. Maybe because, oh yeah. So I did F10 so it could go on in execution and it gave me what is this? The response, that's not what I wanted. Fail to execute JSON response but the steamer is locked. Okay, it seems like it didn't really work as expected. But might have something to do with the debugger. Let me remove the code without the debugger. I'm just going to run it without it being stopped like I did before. Patch.response. Oops. Then response. What happened? Patch.then.response. And there you go. This is what is returning. You can see all of them here. So back here you have to say return response.json because this is a response object. You need to extract that JSON response from JSON data from the response. You have to say .json and that will return a promise that we saw. To handle this promise you can chain it with another .den outside here. And finally that's going to be the entries. And like I said before you can console log it if you want. Save it, that's cool back. Let me remove this breakpoint. Remove all breakpoints. And reload. And here's the console log of all the three entry objects inside an array. Okay, now we need to extract the text of each object and generate a new div here. To do that we're going to do what? Well I have to iterate over each entry in the list and create a new div here. Now to create a new div I have to first use document create element. Remember line three? Then I have to inject the text line five. I have to add a class to style it. Line seven. I have to finally add that to the entry list, line ten. So the same code that's used the add new entry function has to be used here. Well, but I already wrote a function that can be reused so that's the benefit of extracting that behavior that into a function. I can reuse the code here. I need only say add new entry with the entry text. So let's iterate over entries of a loop. So I'm going to say entries dot for each entry. I'm going to do the following. I am going to add that new entry. Well the entry has to have the text. So I'm going to say dot text. Okay, so for each is used to loop over the elements of the array entries. Each element which I call entry is an object. That object has a property text which contains the text that I want. So that's why I use entry dot text to get the value of that. And then I pass this as an argument to the add new entry function which is defined here. And that will create a new element, set the text for that element and add the style and finally append to the list. So this is going to be done three times, right? Because there are three entries. So add new entry what we call three times and it will be added three times here to the list. Let's check it out. There you go. It went fast, right? You can see under the network tab we have the call to get the entries. And this is the response and this response was ultimately used to generate these divs here. If you want to see each one being added slowly, I recommend you go to sources. It's like a debugging practice. Click script.js, that's the file we. And then go to line 18, put a break point, restart, then it's going to pause here. Now what you're going to do is press F8 to click on the display icon and proceed to the next hit of this line. You see it added one on the left. F8 again added the second one. F8 again added the third one. All right. You can see it clearly is adding one by one. Now let me remove this break point. And that's it for this lesson. I'll see you on the next one.
No comments yet (loading...)
No comments yet (loading...)
Did you like the lesson? 😆👍
Consider a donation to support our work: