2021-06-15 00:49:18 -07:00
---
id: 5ccfad82bb2dc6c965a848e5
2021-07-26 03:17:00 +09:00
title: Obter o JSON com o método fetch do JavaScript
2021-06-15 00:49:18 -07:00
challengeType: 6
forumTopicId: 301501
dashedName: get-json-with-the-javascript-fetch-method
---
# --description--
2021-07-26 03:17:00 +09:00
Outra maneira de solicitar dados externos é usar o método `fetch()` do JavaScript. Ele é equivalente ao método `XMLHttpRequest` , mas a sintaxe é considerada mais fácil de entender.
2021-06-15 00:49:18 -07:00
2021-07-26 03:17:00 +09:00
Aqui está o código para fazer uma solicitação de GET para `/json/cats.json`
2021-06-15 00:49:18 -07:00
```js
fetch('/json/cats.json')
2021-07-09 21:23:54 -07:00
.then(response => response.json())
.then(data => {
document.getElementById('message').innerHTML = JSON.stringify(data);
})
2021-06-15 00:49:18 -07:00
```
2021-07-26 03:17:00 +09:00
Dê uma olhada em cada parte deste código.
2021-06-15 00:49:18 -07:00
2021-07-26 03:17:00 +09:00
A primeira linha é aquela que faz a solicitação. Então, `fetch(URL)` faz uma solicitação de `GET` para o URL especificado. O método retorna uma Promise.
2021-06-15 00:49:18 -07:00
2021-07-26 03:17:00 +09:00
Após a devolução da promise, se a solicitação tiver sido bem-sucedida, o método `then` é executado, recebendo a resposta e convertendo-a para o formato JSON.
2021-06-15 00:49:18 -07:00
2021-07-26 03:17:00 +09:00
O método `then` também retorna uma promise, que é tratada pelo próximo método `then` . O argumento no segundo `then` é o objeto do JSON que você está procurando!
2021-06-15 00:49:18 -07:00
2021-07-26 03:17:00 +09:00
Agora, ele seleciona o elemento que receberá os dados usando `document.getElementById()` . Em seguida, modifica o código HTML do elemento, inserindo uma string criada a partir do objeto do JSON retornado pela solicitação.
2021-06-15 00:49:18 -07:00
# --instructions--
2021-07-26 03:17:00 +09:00
Atualize o código para criar e enviar uma solicitação de `GET` para a API de fotos de gatos do freeCodeCamp. Desta vez, porém, use o método `fetch` em vez de `XMLHttpRequest` .
2021-06-15 00:49:18 -07:00
# --hints--
2021-07-26 03:17:00 +09:00
O código deve fazer uma solicitação de `GET` com `fetch` .
2021-06-15 00:49:18 -07:00
```js
assert(code.match(/fetch\s*\(\s*('|")\/json\/cats\.json\1\s*\)/g));
```
2021-07-26 03:17:00 +09:00
O código deve usar `then` para converter a resposta para JSON.
2021-06-15 00:49:18 -07:00
```js
assert(
code.match(
/\.then\s*\(\s*\(?(?< var > \w+)\)?\s*=>\s*\k< var > \s*\.json\s*\(\s*\)\s*\)/g
)
);
```
2021-07-26 03:17:00 +09:00
O código deve usar `then` para lidar com os dados convertidos para JSON pelo outro `then` .
2021-06-15 00:49:18 -07:00
```js
assert(__helpers.removeWhiteSpace(code).match(/\.then\(\(?\w+\)?=>{[^}]*}\)/g));
```
2021-07-26 03:17:00 +09:00
O código deve obter o elemento com o id `message` e alterar seu HTML interno para a string de dados do JSON.
2021-06-15 00:49:18 -07:00
```js
assert(
__helpers.removeWhiteSpace(code).match(
/document\.getElementById\(('|")message\1\)\.innerHTML=JSON\.stringify\(?\w+\)/g
)
);
```
# --seed--
## --seed-contents--
```html
< script >
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick= () => {
// Add your code below this line
// Add your code above this line
};
});
< / script >
< style >
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee ;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0 ;
border-radius: 5px;
border: 1px solid #4791d0 ;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897 ;
border: 1px solid #0F5897 ;
}
< / style >
< h1 > Cat Photo Finder< / h1 >
< p id = "message" class = "box" >
The message will go here
< / p >
< p >
< button id = "getMessage" >
Get Message
< / button >
< / p >
```
# --solutions--
```html
< script >
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick= () => {
fetch('/json/cats.json')
.then(response => response.json())
.then(data => {
document.getElementById('message').innerHTML=JSON.stringify(data);
})
};
});
< / script >
< style >
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee ;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0 ;
border-radius: 5px;
border: 1px solid #4791d0 ;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897 ;
border: 1px solid #0F5897 ;
}
< / style >
< h1 > Cat Photo Finder< / h1 >
< p id = "message" class = "box" >
The message will go here
< / p >
< p >
< button id = "getMessage" >
Get Message
< / button >
< / p >
```