تماشای این درس نیاز به اشتراک حرفه‌ای دارد.

Fetch API Overview0:03

One of the most common things that you will do asynchronously with JavaScript is make a request to the server. And the way that we have done that has drastically changed over time and we are very thankful for that because you know, originally we had an object called XMLHttpRequest. That's a mouthful to say. It was created by Microsoft.

That's a mouthful to say. It was created by Microsoft and you know, it's revolutionized the way that we build web applications, but it was also rather cumbersome, but then third party libraries wrapped around it to make it a lot easier to work with. And that was great, but we needed something native that was easy to work with. And thankfully now we have what's called the fetch API.

Creating ServerStorage File0:37

that was easy to work with. And thankfully now we have what's called the Fetch API. So I've just created the server storage file and this is where we are going to make our requests to the web server to get the game state or at least to manage the game state. In this episode we will get the Game state. So we have this Fetch API and you know, to make simple get requests, it's very easy to use.

Making Basic GET Request1:03

and you know, to make simple GET requests, it's very easy to use. The first thing that we are going to get is a response. Anytime that we call fetch, we will get a response. And this is asynchronous, so I'm going to use await. Now if we didn't use await, we could call fetch and then do something with the response. But I don't wanna do that. I want to await this so that we will fetch and then we just supply the URL

that we will fetch and then we just supply the URL of whatever it is that we want to fetch. In this case, I have a file called GET hp. Now this isn't really going to return any state for us. We are actually going to supply the information that we want it to return just so that you can see how we can make several different kinds of GET requests. But the Fetch API gives us the ability to make any kind of HTTP requests that we might need.

But the Fetch API gives us the ability to make any kind of HTTP requests that we might need. get, post, put, patch, uh, delete. It doesn't matter, you know, the browser itself, at least as far as HTML forms are concerned are limited to just get and post. Not so with JavaScript, with the fetch API, we can make any kind of HTTP request that we might need. Okay, so we are making a fetch request for get php.

Handling Response Errors2:18

Okay, so we are making a fetch request for get php. This is gonna give us a response that we will then need to do something with. The first thing that we need to do is check if the response is okay. Now you know, we think of status code 200 as being okay, but really anything within the range of 200 to 299 would be considered okay?

but really anything within the range of 200 to 299 would be considered, okay? So in the case of the okay property, if it is status 200 through 299, it is considered okay and so therefore we can work with this response. Otherwise it will be false. But let's throw a new Error. Now, I know that we briefly talked about error handling and that you can throw any object, you can catch any object. But if you do want to throw something, you know,

and that you can throw any object, you can catch any object. But if you do want to throw something, you know, from a semantic standpoint, throwing an Error is pretty good because it, it's clear as to what you were doing. You are throwing an Error that will have a message of response wasn't okay. Now you can achieve essentially the same result by just throwing an object that has a message property and then give it that value.

Parsing Response Body3:30

by just throwing an object that has a message property and then give it that value. But if you throw a new Error, it's clear what you're doing, you're throwing a new Error. Now if we do have an ok response, then we need to work with the body of that response. And the way that we do that is with some methods. So these are asynchronous as well. So we want to await them and most of the time we are going to be dealing with text

So we want to await them and most of the time we are going to be dealing with text because we are fetching some kind of data from the server. So we can call the text method and that is going to take the body of the response and return it as text so that we can do whatever it is that we need to. So that means if we are working with JSON structure, we can take that text and then we can parse it into an object.

we can take that text and then we can parse it into an object. But if that's what we need to do, then there's another method called json, which is going to automatically do that for us. So if we call the json method, it's going to return a JavaScript object that parsed the text body from the response. So it, it is just an extra step that we don't have to do anymore if, if we know

So it, it is just an extra step that we don't have to do anymore if, if we know that we are getting json from the server. But then if we are working with binary, we have the blob method and then we can work with that from there. In our case, we are getting an adjacent response from the server. So we want that to go ahead, parse it into an object that we can use, in which case then we can

So we want that to go ahead, parse it into an object that we can use, in which case then we can just return the body. But really we could just simplify this so that we return await response json, and there we go. That's going to give us the game state. Now currently this gets PHP file, uh, automatically just returns null. So if we take a look at this inside of the browser, it's not gonna prompt us to load the saved game.

Building Query Parameters5:18

So if we take a look at this inside of the browser, it's not gonna prompt us to load the saved game because it returns null by default. If we want some state information to work with, we need to supply that ourselves with the request. And since this is a GET request, that means that we have to include all of the information within the query string. So that means we need to add minRange and then whatever value. And if I could find the, and where is it?

and then whatever value. And if I could find the, and where is it? It's seven and max range. You know, we could do it like that, but a lot of times we have the information that we need but it would be in the shape of an object or something like that. In which case we don't have to do that. We can create a Params object by newing up URLSearchParams.

We can create a Paras object by newing up UrlSearchParas. This is a type of object that is going to take whatever object we supply it and it's going to parse it into a query stream that we can just add onto a URL. So in our case we have minRange. Let's give it a value of 1 maxRange. Let's give it a value of 10 maxAttempts. Uh, let's do 5

Let's give it a value of 10 max attempts. Uh, let's do 5 and then what else allow duplicate guesses? Is that what it is? Uh, false. And then we need the secret number, which let's say that that will be 7, okay? We're not going to include history because you know, that can get a little wonky with the URL parameters. So we're just gonna stick with this

with the URL parameters. So we're just gonna stick with this and then we need to include that with our request, in which case we'll just include that there. It will automatically parse it into a query stream so that inside of the browser, whenever we refresh, nothing happens. And you know why? Because we didn't change the Game class. We need to import from ServerStorage.

Debugging in Network Tab7:17

change the Game class. We need to import from server storage. Okay, I already did that. I didn't do that on screen, but I did that for another take. So just be sure inside of game.js to change your import from the browser storage to the server storage, that's kind of important for this to work. So now let's pull up the developer tools. Let's do a hard refresh here.

So now let's pull up the developer tools. Let's do a hard refresh here and yeah, okay, so we are making a request here. We can see that request going out right there and it is initiating from server storage, but we're not getting the response that I was hoping for. We can inspect this, we can go to the response and there is an error in the JSON syntax. So undefined array key allowDuplicateGuesses. Okay, fine, what is it?

So undefined array key allowDuplicateGuesses. Okay, fine, what is it? Let's open up get php, allowDuplicateGuesses. Isn't that what I typed? No, it's not what I typed. So be careful what you type. Okay, so with that done, we can refresh and now we see, do you want to continue the saved game? So now we are making a request to the server. We are getting the response parsing in that into a JavaScript object.

We are getting the response parsing in that into a JavaScript object. And then voila, we can see that we have a game to start and we know what those parameters are. So if we just go ahead and guess seven, then this should work. But you know, one thing I wanted to point out in that whenever you make a request with JavaScript, it is going to be part of the network tab in your developer tools. So you can go in, you can see that request going out.

to be part of the network tab in your developer tools. So you can go in, you can see that request going out and you can inspect that so that you can see what kind of response you are getting, which in our case, that was very beneficial because it would've taken me a while to figure out why my request wasn't working and it was because I mistyped something. So there we go. Now there's one other thing that I want to talk about and that is adding headers

Adding Request Headers9:23

So there we go. Now there's one other thing that I want to talk about and that is adding headers because that is something that is also very common. So the easiest way to use fetch is to just provide the URL that you want to make a request to, but sometimes you need to supply some other options in which case you pass a second argument, which is an options object. And we'll be dealing more with this in the next episode. But for right now, I want to set some headers,

And we'll be dealing more with this in the next episode. But for right now, I want to set some headers, one being Accept. Now in our case, we will always get a JSON structure back from the server, but I want to go ahead and set Accept to application/json because a lot of times that's what we need to do in order to tell the server that, Hey, we want JSON back. So we want to include the Accept header. This is also where we would set the Authorization header.

So we want to include the Accept header. This is also where we would set the Authorization header. If we had a BearerToken to work with an API or something along like that, we could include the Authorization header there. But for right now, I just want the Accept header and that's not going to change anything as far as our particular code is concerned because it's always going to return JSON. But that is how you can set headers.

because it's always going to return Jason. But that is how you can set headers. But once again, refreshing, we see that we get our gameState object, we can see what is coming back from that request and then we can choose do we want to continue the game or no, maybe not. Let's just play a new Medium game. And so that's essentially it. Making GET requests is very simple with the Fetch API.

And so that's essentially it. Making GET requests is very simple with the Fetch API. In the next episode, we will look at making POST requests so that we can save our game state.

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟