|
| 1 | +## 17-Making-HTTP-Requests |
| 2 | + |
| 3 | +## 1. Intro to AJAX |
| 4 | + |
| 5 | +### REQUESTS |
| 6 | + |
| 7 | +- XMLHTTP |
| 8 | +- FETCH |
| 9 | +- AXIOS |
| 10 | + |
| 11 | +### AJAX |
| 12 | + |
| 13 | +- ASYNCHRONOUS |
| 14 | +- JAVASCRIPT |
| 15 | +- AND |
| 16 | +- XML |
| 17 | + |
| 18 | +Back in the day before, AJAX was really a big thing. Before single page apps SPA we common, we had one standard flow for loading new data or getting information from a server which included a page refresh. |
| 19 | + |
| 20 | +Example: Go to MDN website and search for the **div** word and hit enter. |
| 21 | + |
| 22 | +So what's happening here is the browser is sending a request for a new webpage and it's going off to one of MDN servers depending on this URL `https://developer.mozilla.org/en-US/search?q=div`, this is the URL that we requested by hitting enter. This URL is then received, the request is received by the server, and it compiles a new webpage for us, including the HTML, CSS and any relevant JavaScript. It sends the entire page back, our browser refreshes and this is what we see, a whole new page. |
| 23 | + |
| 24 | +Contrast that with the `https://caniuse.com` page. Search for gradient, the page never reloads, I don't go anywhere else. Data is being loaded, there is communication with the server, but it's happening behind the scenes. It doesn't involve a whole page refresh, we're not getting a new webpage, It's a different approach. |
| 25 | + |
| 26 | +We're just getting some data, the webpage is asking for data from a server. It comes back and then new elements are added to the page, the page is changing, the contents are changing, at least some of it. But it's a single page SPA that we are staying on. |
| 27 | + |
| 28 | +**This is really what AJAX is all about** |
| 29 | + |
| 30 | +The idea of **AJAX** is using these requests that we can make via JavaScript asynchronously to load some data from a server or to send data to a server to save something to a database, whatever it is, we're communicating with a server behind the scenes. |
| 31 | + |
| 32 | +Not in between page loads like the MDN example, in between those loads, in between what a user sees and the page refreshing, that is when the communication is occurring with the server. |
| 33 | + |
| 34 | +With SPA example the communication is happening while i'm on this page. It's happening in the background. We get some response from the server. |
| 35 | + |
| 36 | +The response usually these days is in the form of something called **JSON**. In the past, it was **XML**, which is what was most commonly used and where the name AJAX comes from. But these days almost everyone uses JSON |
| 37 | + |
| 38 | +So **JSON** is just a format for sending data. Imagine you have data representing all of this information (Previous Example) `https://caniuse.com` we see here. |
| 39 | + |
| 40 | +The elements themselves are not being sent as HTML or the CSS is not being sent. All that's being sent is basically the text and some information that maybe doesn't show up, you know what's supported what's not supported, and it's being sent as text |
| 41 | + |
| 42 | +But rather than just plain text, it's turned into this **JSON** notation. It's a way of representing data. It's a protocol for communicating between servers or a protocol for formatting data and sending it to another server or to another browser somewhere. |
| 43 | + |
| 44 | +#### See the request happening behind the scenes |
| 45 | + |
| 46 | +- Go to Chrome Dev Tools |
| 47 | +- Open the network tab |
| 48 | +- Go to https://caniuse.com |
| 49 | +- Search for **spread** in the search bar, hit enter |
| 50 | +- Check the network activity |
| 51 | + |
| 52 | +This network activity represents different kinds of requests that have been sent. |
| 53 | + |
| 54 | +If we go to XHR tab, is going to show us the requests that have been sent. This is one `query.php?search=spread` and some information was sent back, this is the data that was sent back by the server. |
| 55 | + |
| 56 | +But the point is, this is not HTML that's being sent. It's not JavaScript itself. It looks like JavaScript but it's actually called **JSON**. It's simply a way of sharing data between a server and another server, a server and a browser that we can then use in JavaScript. |
| 57 | + |
| 58 | +It's really easy to take JSON and turn it into JavaScript and do something with it. |
| 59 | + |
| 60 | +## 2. JSON & XML |
| 61 | + |
| 62 | +XML Extensible Markup Language and JSON JavaScript Object Notation, So these are two ways of basically formatting data so that you can send it from a server to another server, or a server to a browser. |
| 63 | + |
| 64 | +It's a format for information they both solve essentially the same problem. We have some data that we want to send. We need to figure out a common standard way of sending that information. |
| 65 | + |
| 66 | +#### XML example |
| 67 | + |
| 68 | +```xml |
| 69 | +<!-- name -> @ElfGodd |
| 70 | +email -> elfgodd@elfgodd.com |
| 71 | +age -> 36 --> |
| 72 | +<name> |
| 73 | + <first>Elf</first> |
| 74 | + <first>Godd</first> |
| 75 | +</name> |
| 76 | +<email>elfgodd@elfgodd.com</email> |
| 77 | +``` |
| 78 | + |
| 79 | +**In JavaScript we have a way of taking data in XML and turning it into a JavaScript Object** |
| 80 | + |
| 81 | +#### JavaScript Object example |
| 82 | + |
| 83 | +```javascript |
| 84 | +{ |
| 85 | + name: { |
| 86 | + first: 'Elf', |
| 87 | + last: 'Godd' |
| 88 | + }, |
| 89 | + email: 'elfgodd@elfgodd.com' |
| 90 | +} |
| 91 | +``` |
| 92 | + |
| 93 | +#### JSON |
| 94 | + |
| 95 | +```json |
| 96 | +{ |
| 97 | + "squadName": "Super hero squad", |
| 98 | + "homeTown": "Metro City", |
| 99 | + "formed": 2016, |
| 100 | + "secretBase": "Super tower", |
| 101 | + "active": true, |
| 102 | + "members": ["Molecule Man", "Madame Uppercut", "Eternal Flame"] |
| 103 | +} |
| 104 | +``` |
| 105 | + |
| 106 | +Every key in JSON must be a string with quotes. We also can use arrays, We can have values like numbers, booleans, strings, but we cannot store more complicated things like functions as an example. |
| 107 | + |
| 108 | +**We can translate between JSON and JavaScript very, very easily** |
| 109 | + |
| 110 | +- SWAPI API a Star Wars API that we can play around with `https://swapi.co`. |
| 111 | + |
| 112 | +- JSON Formatter & validator `https://jsonformatter.curiousconcept.com`. |
| 113 | + |
| 114 | +create an international phonetic alphabet with examples |
| 115 | + |
| 116 | +## 3. XMLHttpRequest |
| 117 | + |
| 118 | +- The "original" way of sending requests via JS. |
| 119 | +- Does not support promises, so...lots of callbacks! |
| 120 | +- WTF is going on with the weird capitalization? |
| 121 | +- Clunky syntax that i find difficult to remember! |
| 122 | + |
| 123 | +Making our first request using XMLHttpRequest through JavaScript. So these are objects in the browser we can create that have different methods and we can use them to fetch data from an API to send data somewhere. |
| 124 | + |
| 125 | +So we end up with a lot of callbacks, if we have nested requests, things where we want to make one request, get information back and then make a second request. |
| 126 | + |
| 127 | +This was the only way of making a request **XMLHttpRequest** |
| 128 | + |
| 129 | +```javascript |
| 130 | +const myReq = new XMLHttpRequest() |
| 131 | + |
| 132 | +myReq.onload = function () { |
| 133 | + const data = JSON.parse(this.responseText) |
| 134 | + console.log(data) |
| 135 | +} |
| 136 | +myReq.onerror = function (err) { |
| 137 | + console.log('ERROR!', err) |
| 138 | +} |
| 139 | +myReq.open('get', 'https://icanhazdadjoke..com/', true) |
| 140 | +myReq.setRequestHeader('Accept', 'application/json') |
| 141 | +myReq.send() |
| 142 | +``` |
| 143 | + |
| 144 | +## 4. XMLHttpRequests Chaining Requests |
| 145 | + |
| 146 | +## 5. A Better Way Fetch |
| 147 | + |
| 148 | +#### Fetch |
| 149 | + |
| 150 | +- The newer way of making requests via JS |
| 151 | +- Supports promises! |
| 152 | + |
| 153 | +```javascript |
| 154 | +fetch('https://icanhazdadjoke.com/23/2', { |
| 155 | + headers: { Accept: 'application/json' }, |
| 156 | +}) |
| 157 | + .then((res) => { |
| 158 | + if (res.status !== 200) { |
| 159 | + console.log('Problem!', res.status) |
| 160 | + return |
| 161 | + } |
| 162 | + res.json().then((data) => { |
| 163 | + console.log(data) |
| 164 | + }) |
| 165 | + }) |
| 166 | + .catch(function (err) { |
| 167 | + console.log('Fetch Error', err) |
| 168 | + }) |
| 169 | +``` |
| 170 | + |
| 171 | +#### Fetch API MDN: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API |
| 172 | + |
| 173 | +## 6. Chaining Fetch Requests |
| 174 | + |
| 175 | +## 7. Refactoring Fetch Chains |
| 176 | + |
| 177 | +## 8. An Even Better Way Axios |
| 178 | + |
| 179 | +#### AXIOS |
| 180 | + |
| 181 | +A LIBRARY FOR MAKING HTTP REQUESTS |
| 182 | + |
| 183 | +Next up, we have a third option for making requests via JavaScript. This is not a built in option, it's not native JavaScript like Fetch or XHR. |
| 184 | + |
| 185 | +It is a external library called **Axios** it's one of many a whole bunch of different HTTP libraries that you could use. **Axios** is just the most popular. |
| 186 | + |
| 187 | +#### https://github.com/axios/axios |
| 188 | + |
| 189 | +So all that it does is it simplifies the process of making requests. It uses fetch behind the scenes so it doesn't give us anything we can't already do. |
| 190 | + |
| 191 | +It just simplifies things through a bunch of methods and objects that it creates that we can interact with. It is promise based just like fetch. |
| 192 | + |
| 193 | +You can use it both in the client on the browser side of things, but also on the server side using NodeJS |
| 194 | + |
| 195 | +#### Run in the Chrome browser |
| 196 | + |
| 197 | +```javascript |
| 198 | +// 1. const res = axios.get('https://swapi.dev/api/planets/') |
| 199 | +// 2. res |
| 200 | +// 3. Open Promise, then PromiseResult, then Open Data |
| 201 | +``` |
| 202 | + |
| 203 | +I get a promise back, save it to a variable **res**. So just like **Fetch** we get a promise back when we make a request using **Axios**. Let's take a look at the value that it's been resolved with. |
| 204 | + |
| 205 | +Inside we have a data property and it's already been parsed for us. We don't have to parsed it ourselves. That's one of the main advantages of using a tool like Axios, is that unlike Fetch, we don't have to do the **JSON parsing** on our own. |
| 206 | + |
| 207 | +## 9. Sequential Axios Requests |
| 208 | +Let's see how we can use **Axios** to make multiple chain requests, |
0 commit comments