--- id: 5ccfad82bb2dc6c965a848e5 title: 使用 JavaScript 的 fetch 方法獲取 JSON challengeType: 6 forumTopicId: 301501 dashedName: get-json-with-the-javascript-fetch-method --- # --description-- 請求外部數據的另一個方法是使用 JavaScript 的 `fetch()` 方法。 它的作用和 `XMLHttpRequest` 一樣,但是它的語法更容易理解。 下面是使用 GET 請求 `/json/cats.json` 數據的例子。 ```js fetch('/json/cats.json') .then(response => response.json()) .then(data => { document.getElementById('message').innerHTML = JSON.stringify(data); }) ``` 逐行解釋一下代碼。 第一行是發起請求。 `fetch(URL)` 向指定的 URL 發起 `GET` 請求。 這個方法返回一個 Promise。 當 Promise 返回後,如果請求成功,會執行 `then` 方法,該方法把響應轉換爲 JSON 格式。 `then` 方法返回的也是 Promise,會被下一個 `then` 方法捕獲。 第二個 `then` 方法傳入的參數就是最終的 JSON 對象。 接着,使用 `document.getElementById()` 選擇將要接收數據的元素。 然後插入請求返回的 JSON 對象創建的字符串修改元素的 HTML 代碼。 # --instructions-- 更新代碼,創建並向 freeCodeCamp Cat Photo API 發送 `GET` 請求。 這次使用 `fetch` 方法而不是 `XMLHttpRequest`。 # --hints-- 應該使用 `fetch` 發起 `GET` 請求。 ```js assert(code.match(/fetch\s*\(\s*('|")\/json\/cats\.json\1\s*\)/g)); ``` 應該在 `then` 裏面將響應轉換爲 JSON。 ```js assert( code.match( /\.then\s*\(\s*\(?(?\w+)\)?\s*=>\s*\k\s*\.json\s*\(\s*\)\s*\)/g ) ); ``` 應該使用另一個 `then` 接收 `then` 轉換的 JSON。 ```js assert(__helpers.removeWhiteSpace(code).match(/\.then\(\(?\w+\)?=>{[^}]*}\)/g)); ``` 代碼應該選擇 id 爲 `message` 的元素然後把它的內部 HTML 改成 JSON data 的字符串。 ```js assert( __helpers.removeWhiteSpace(code).match( /document\.getElementById\(('|")message\1\)\.innerHTML=JSON\.stringify\(?\w+\)/g ) ); ``` # --seed-- ## --seed-contents-- ```html

Cat Photo Finder

The message will go here

``` # --solutions-- ```html

Cat Photo Finder

The message will go here

```