fetch()
method. It is equivalent to XMLHttpRequest, but the syntax is considered easier to understand.
+Here is the code for making a GET request to /json/cats.json
+
+```js
+
+fetch('/json/cats.json')
+ .then(response => response.json())
+ .then(data => {
+ document.getElementById('message').innerHTML = JSON.stringify(data);
+ })
+
+```
+
+Take a look at each piece of this code.
+
+The first line is the one that makes the request. So, fetch(URL)
makes a GET request to the URL specified. The method returns a Promise.
+
+After a Promise is returned, if the request was successful, the then
method is executed, which takes the response and converts it to JSON format.
+
+The then
method also returns a Promise, which is handled by the next then
method. The argument in the second then
is the JSON object you are looking for!
+
+Now, it selects the element that will receive the data by using document.getElementById()
. Then it modifies the HTML code of the element by inserting a string created from the JSON object returned from the request.
+fetch
method instead of XMLHttpRequest
.
+fetch
.
+ testString: assert(code.match(/fetch\s*\(\s*('|")\/json\/cats\.json\1\s*\)/g));
+ - text: Your code should use then
to convert the response to JSON.
+ testString: assert(code.match(/\.then\s*\(\s*(response|\(\s*response\s*\))\s*=>\s*response\s*\.json\s*\(\s*\)\s*\)/g))
+ - text: Your code should use then
to handle the data converted to JSON by the other then
.
+ testString: assert(code.match(/\.then\s*\(\s*(data|\(\s*data\s*\))\s*=>\s*{[^}]*}\s*\)/g))
+ - text: Your code should get the element with id message
and change its inner HTML to the string of JSON data.
+ testString: assert(code.match(/document\s*\.getElementById\s*\(\s*('|")message\1\s*\)\s*\.innerHTML\s*=\s*JSON\s*\.\s*stringify\s*\(\s*data\s*\)/g));
+
+```
+
++ The message will go here +
++ +
+``` + ++ The message will go here +
++ +
+``` + +