Você está na página 1de 9

const xhr = new XMLHttpRequest(); fetch('https://api-to- const getData = async () => {

const url = 'https://api-to-call.com/endpoint'; call.com/endpoint').then(response => { try {


xhr.responseType = 'json'; if (response.ok) { const response = await fetch('https://api-to-
xhr.onreadystatechange = () => { return response.json(); call.com/endpoint');
if (xhr.readyState === XMLHttpRequest.DONE){ } if (response.ok) {
return xhr.response; throw new Error('Request failed!'); const jsonResponse = await response.json();
} }, networkError => { return jsonResponse;
} console.log(networkError.message); }
}).then(jsonResponse => { throw new Error('Request failed!');
xhr.open('GET', url); return jsonResponse; } catch (error) {
xhr.send(); }); console.log(error);
}
}

const xhr = new XMLHttpRequest(); fetch('https://api-to-call.com/endpoint', { const getData = async () => {


const url = 'https://api-to-call.com/endpoint'; method: 'POST', try {
const data = JSON.stringify({id: '200'}); body: JSON.stringify({id: "200"}) const response = await fetch('https://api-to-
}).then(response => { call.com/endpoint', {
xhr.responseType = 'json'; if(response.ok){ method: 'POST',
return response.json(); body: JSON.stringify({id: 200})
xhr.onreadystatechange = () => { } })
if(xhr.readyState === XMLHttpRequest.DONE){ throw new Error('Request failed!'); if(response.ok){
return xhr.response; }, networkError => { const jsonResponse = await response.json();
} console.log(networkError.message); return jsonResponse;
} }).then(jsonResponse => { }
console.log(jsonResponse); throw new Error('Request failed!');
xhr.open('POST', url); }) } catch(error) {
xhr.send(data); console.log(error);
}
}
// Information to reach API // Information to reach API // Information to reach API
const url = 'https://api.datamuse.com/words?'; const url = 'https://api.datamuse.com/words'; const url = 'https://api.datamuse.com/words?';
const queryParams = 'rel_rhy='; const queryParams = '?sl='; const queryParams = 'rel_jja=';

// Selecting page elements // Selects page elements // Selecting page elements


const inputField = document.querySelector('#input'); const inputField = document.querySelector('#input'); const inputField = document.querySelector('#input');
const submit = document.querySelector('#submit'); const submit = document.querySelector('#submit'); const submit = document.querySelector('#submit');
const responseField = const responseField = const responseField =
document.querySelector('#responseField'); document.querySelector('#responseField'); document.querySelector('#responseField');

// AJAX function // AJAX function // AJAX function


const getSuggestions = () => { const getSuggestions = () => { // Code goes here
const wordQuery = inputField.value; const wordQuery = inputField.value; const getSuggestions = async () => {
const endpoint = `${url}${queryParams}${wordQuery}`; const endpoint = `${url}${queryParams}${wordQuery}`; const wordQuery = inputField.value;
const endpoint = `${url}${queryParams}${wordQuery}`;
const xhr = new XMLHttpRequest(); fetch(endpoint).then(response => { try {
xhr.responseType = 'json'; if (response.ok) { const response = await fetch(endpoint);
return response.json(); if(response.ok){
xhr.onreadystatechange = () => { } const jsonResponse = await response.json();
if (xhr.readyState === XMLHttpRequest.DONE) { throw new Error('Request failed!'); renderResponse(jsonResponse);
renderResponse(xhr.response); }, networkError => { }
} console.log(networkError.message) } catch (error) {
} }).then(jsonResponse => { console.log(error);
renderResponse(jsonResponse); }
xhr.open('GET', endpoint); }) }
xhr.send(); }
} // Clear previous results and display results to webpage
// Clears previous results and display results to webpage const displaySuggestions = (event) => {
// Clear previous results and display results to webpage const displaySuggestions = (event) => { event.preventDefault();
const displaySuggestions = (event) => { event.preventDefault(); while(responseField.firstChild){
event.preventDefault(); while(responseField.firstChild){ responseField.removeChild(responseField.firstChild);
while(responseField.firstChild){ responseField.removeChild(responseField.firstChild); }
responseField.removeChild(responseField.firstChild); } getSuggestions();
} getSuggestions(); }
getSuggestions(); };
} submit.addEventListener('click', displaySuggestions);
submit.addEventListener('click', displaySuggestions);
submit.addEventListener('click', displaySuggestions);
// Formats response to look presentable on webpage // Formats response to look presentable on webpage // Formats response to look presentable on webpage
const renderResponse = (res) => { const renderResponse = (res) => { const renderResponse = (res) => {
// handles if res is falsey // Handles if res is falsey // Handles if res is falsey
if(!res){ if(!res){ if(!res){
console.log(res.status) console.log(res.status); console.log(res.status);
} } }
// in case res comes back as a blank array // In case res comes back as a blank array // In case res comes back as a blank array
if(!res.length){ if(!res.length){ if(!res.length){
responseField.innerHTML = "<p>Try again!</p><p>There responseField.innerHTML = "<p>Try again!</p><p>There responseField.innerHTML = "<p>Try
were no suggestions found!</p>" were no suggestions found!</p>"; again!</p><p>There were no suggestions found!</p>";
return return; return;
} } }

// creating an array to contain the HTML strings // Creates an empty array to contain the HTML strings // Creates an empty array to contain the HTML strings
let wordList = [] let wordList = []; let wordList = [];
// looping through the response and maxxing out at 10 // Loops through the response and caps off at 10 // Loops through the response and caps off at 10
for(let i = 0; i < Math.min(res.length, 10); i++){ for(let i = 0; i < Math.min(res.length, 10); i++){ for(let i = 0; i < Math.min(res.length, 10); i++){
// creating a list of words // creating a list of words // creating a list of words
wordList.push(`<li>${res[i].word}</li>`) wordList.push(`<li>${res[i].word}</li>`); wordList.push(`<li>${res[i].word}</li>`);
} } }
// joins the array of HTML strings into one string // Joins the array of HTML strings into one string // Joins the array of HTML strings into one string
wordList = wordList.join("") wordList = wordList.join(""); wordList = wordList.join("");

// manipulates responseField to render the modified // Manipulates responseField to render the modified // Manipulates responseField to render the modified
response response response
responseField.innerHTML = `<p>You might be interested responseField.innerHTML = `<p>You might be interested responseField.innerHTML = `<p>You might be interested
in:</p><ol>${wordList}</ol>` in:</p><ol>${wordList}</ol>`; in:</p><ol>${wordList}</ol>`;
return return return
} } }

// Renders response before it is modified // Renders response before it is modified // Renders response before it is modified
const renderRawResponse = (res) => { const renderRawResponse = (res) => { const renderRawResponse = (res) => {
// taking the first 10 words from res // Takes the first 10 words from res // Takes the first 10 words from res
let trimmedResponse = res.slice(0, 10) let trimmedResponse = res.slice(0, 10); let trimmedResponse = res.slice(0, 10);
//manipulates responseField to render the unformatted // Manipulates responseField to render the unformatted // Manipulates responseField to render the unformatted
response response response
responseField.innerHTML = responseField.innerHTML = responseField.innerHTML =
`<text>${JSON.stringify(trimmedResponse)}</text>` `<text>${JSON.stringify(trimmedResponse)}</text>`; `<text>${JSON.stringify(trimmedResponse)}</text>`;
} } }

// Renders the JSON that was returned when the Promise // Renders the JSON that was returned when the Promise from // Renders the JSON that was returned when the Promise
from fetch resolves. fetch resolves. from fetch resolves.
const renderJsonResponse = (res) => { const renderJsonResponse = (res) => { const renderJsonResponse = (res) => {
// creating an empty object to store the JSON in key-value // Creates an empty object to store the JSON in key-value // Creates an empty object to store the JSON in key-value
pairs pairs pairs
let rawJson = {} let rawJson = {}; let rawJson = {};
for(let key in response){ for(let key in res){ for(let key in response){
rawJson[key] = response[key] rawJson[key] = res[key]; rawJson[key] = response[key];
} } }
// converting JSON into a string and adding line breaks to // Converts JSON into a string and adding line breaks to make // Converts JSON into a string and adding line breaks to
make it easier to read it easier to read make it easier to read
rawJson = JSON.stringify(rawJson).replace(/,/g, ", \n") rawJson = JSON.stringify(rawJson).replace(/,/g, ", \n"); rawJson = JSON.stringify(rawJson).replace(/,/g, ", \n");
// manipulates responseField to show the returned JSON. // Manipulates responseField to show the returned JSON. // Manipulates responseField to show the returned
responseField.innerHTML = `<pre>${rawJson}</pre>` responseField.innerHTML = `<pre>${rawJson}</pre>`; JSON.
} } responseField.innerHTML = `<pre>${rawJson}</pre>`;
}

// Information to reach API // Information to reach API // information to reach API


const apiKey = '<Your API Key>'; const apiKey = '<Your API Key>'; const apiKey = '<Your API Key>';
const url = 'https://api.rebrandly.com/v1/links'; const url = 'https://api.rebrandly.com/v1/links'; const url = 'https://api.rebrandly.com/v1/links';

// Some page elements // Some page elements // Some page elements


const inputField = const inputField = const inputField =
document.querySelector('#input'); document.querySelector('#input'); document.querySelector('#input');
const shortenButton = const shortenButton = const shortenButton =
document.querySelector('#shorten'); document.querySelector('#shorten'); document.querySelector('#shorten');
const responseField = const responseField = const responseField =
document.querySelector('#responseField'); document.querySelector('#responseField'); document.querySelector('#responseField');

// AJAX functions // AJAX functions // AJAX functions


const shortenUrl = () => { const shortenUrl = () => { // Code goes here
const urlToShorten = inputField.value; const urlToShorten = inputField.value; const shortenUrl = async () => {
const data = JSON.stringify({destination: const data = JSON.stringify({destination: const urlToShorten = inputField.value;
urlToShorten}); urlToShorten}) const data = JSON.stringify({destination:
urlToShorten});
const xhr = new XMLHttpRequest(); fetch(url, { try {
xhr.responseType = 'json'; method: 'POST', const response = await fetch(url, {
headers: { method: 'POST',
xhr.onreadystatechange = () => { 'Content-type': 'application/json', body: data,
if (xhr.readyState === XMLHttpRequest.DONE) { 'apikey': apiKey headers: {
}, 'Content-type': 'application/json',
renderResponse(xhr.response); body: data 'apikey':
} }).then(response => { apiKey
} if (response.ok) { }
xhr.open('POST', url); return response.json(); });
xhr.setRequestHeader('Content-type', } if(response.ok){
'application/json'); throw new Error('Request failed!'); const jsonResponse = await response.json();
xhr.setRequestHeader('apikey', apiKey); }, networkError => { renderResponse(jsonResponse);
xhr.send(data); console.log(networkError.message) }
} }).then(jsonResponse => { } catch (error) {
renderResponse(jsonResponse); console.log(error);
}) }
// Clear page and call AJAX functions } }
const displayShortUrl = (event) => {
event.preventDefault(); // Clear page and call AJAX functions // Clear page and call AJAX functions
while(responseField.firstChild){ const displayShortUrl = (event) => { const displayShortUrl = (event) => {
event.preventDefault(); event.preventDefault();
responseField.removeChild(responseField.firstChild); while(responseField.firstChild){ while(responseField.firstChild){
}
shortenUrl(); responseField.removeChild(responseField.firstChild) responseField.removeChild(responseField.firstChild);
} } }
shortenUrl(); shortenUrl();
shortenButton.addEventListener('click', } }
displayShortUrl);
shortenButton.addEventListener('click', shortenButton.addEventListener('click',
displayShortUrl); displayShortUrl);
// manipulate responseField to render a formatted // Manipulates responseField to render a formatted // Manipulates responseField to render a formatted
and appropriate message and appropriate message and appropriate message
const renderResponse = (res) => { const renderResponse = (res) => { const renderResponse = (res) => {
if(res.errors){ // Displays either message depending on results // Displays either message depending on results
responseField.innerHTML = "<p>Sorry, couldn't if(res.errors){ if(res.errors){
format your URL.</p><p>Try again.</p>" responseField.innerHTML = "<p>Sorry, couldn't responseField.innerHTML = "<p>Sorry, couldn't
} else { format your URL.</p><p>Try again.</p>"; format your URL.</p><p>Try again.</p>";
responseField.innerHTML = `<p>Your shortened } else { } else {
url is: </p><p> ${res.shortUrl} </p>` responseField.innerHTML = `<p>Your shortened responseField.innerHTML = `<p>Your shortened
} url is: </p><p> ${res.shortUrl} </p>`; url is: </p><p> ${res.shortUrl} </p>`;
} } }
} }
// manipulate responseField to render an
unformatted response // Manipulates responseField to render an // Manipulates responseField to render an
const renderRawResponse = (res) => { unformatted response unformatted response
if(res.errors){ const renderRawResponse = (res) => { const renderRawResponse = (res) => {
responseField.innerHTML = "<p>Sorry, couldn't // Displays either message depending on results // Displays either message depending on results
format your URL.</p><p>Try again.</p>" if(res.errors){ if(res.errors){
} else { responseField.innerHTML = "<p>Sorry, couldn't responseField.innerHTML = "<p>Sorry, couldn't
let structuredRes = format your URL.</p><p>Try again.</p>"; format your URL.</p><p>Try again.</p>";
JSON.stringify(res).replace(/,/g, ", \n") } else { } else {
structuredRes = `<pre>${structuredRes}</pre>` // Adds line breaks for JSON // Adds line breaks for JSON
let structuredRes = let structuredRes =
responseField.innerHTML = `${structuredRes}` JSON.stringify(res).replace(/,/g, ", \n"); JSON.stringify(res).replace(/,/g, ", \n");
} structuredRes = `<pre>${structuredRes}</pre>`; structuredRes = `<pre>${structuredRes}</pre>`;
} responseField.innerHTML = `${structuredRes}`; responseField.innerHTML = `${structuredRes}`;
} }
} }

// Renders the JSON that was returned when the


Promise from fetch resolves.
const renderJsonResponse = (response) => {
// Creates an empty object to store the JSON in
key-value pairs
let rawJson = {}
for(let key in response){
rawJson[key] = response[key]
}
// Converts JSON into a string and adding line
breaks to make it easier to read
rawJson = JSON.stringify(rawJson).replace(/,/g, ",
\n")
// Manipulates responseField to show the
returned JSON.
responseField.innerHTML =
`<pre>${rawJson}</pre>`
}

// Information to reach API


const url = 'https://api.datamuse.com/words?';
const queryParams = 'rel_jjb=';
const additionalParams = '&topics=';

// Selecting page elements


const inputField = document.querySelector('#input');
const topicField = document.querySelector('#topic');
const submit = document.querySelector('#submit');
const responseField = document.querySelector('#responseField');

// AJAX function
const getSuggestions = () => {
const wordQuery = inputField.value;
const topicQuery = topicField.value;
const endpoint =
`${url}${queryParams}${wordQuery}${additionalParams}${topicQuery}`;

const xhr = new XMLHttpRequest();


xhr.responseType = 'json';

xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
renderResponse(xhr.response);
}
}

xhr.open('GET', endpoint);
xhr.send();
}

// Clear previous results and display results to webpage


const displaySuggestions = (event) => {
event.preventDefault();
while(responseField.firstChild){
responseField.removeChild(responseField.firstChild);
}
getSuggestions();
}

submit.addEventListener('click', displaySuggestions);
// Formats response to look presentable on webpage
const renderResponse = (res) => {
// handles if res is falsey
if(!res){
console.log(res.status)
}
// in case res comes back as a blank array
if(!res.length){
responseField.innerHTML = "<p>Try again!</p><p>There were no
suggestions found!</p>"
return
}

// creating an array to contain the HTML strings


let wordList = []
// looping through the response and maxxing out at 10
for(let i = 0; i < Math.min(res.length, 10); i++){
// creating a list of words
wordList.push(`<li>${res[i].word}</li>`)
}
// joins the array of HTML strings into one string
wordList = wordList.join("")

// manipulates responseField to render the modified response


responseField.innerHTML = `<p>You might be interested
in:</p><ol>${wordList}</ol>`
return
}

// Renders response before it is modified


const renderRawResponse = (res) => {
// taking the first 10 words from res
let trimmedResponse = res.slice(0, 10)
//manipulates responseField to render the unformatted response
responseField.innerHTML =
`<text>${JSON.stringify(trimmedResponse)}</text>`
}

// Renders the JSON that was returned when the Promise from fetch
resolves.
const renderJsonResponse = (res) => {
// creating an empty object to store the JSON in key-value pairs
let rawJson = {}
for(let key in response){
rawJson[key] = response[key]
}
// converting JSON into a string and adding line breaks to make it
easier to read
rawJson = JSON.stringify(rawJson).replace(/,/g, ", \n")
// manipulates responseField to show the returned JSON.
responseField.innerHTML = `<pre>${rawJson}</pre>`
}

// NOTE: wordSmith functions from lines 4 - 39


// NOTE: byteSize functions from lines 41 - 76
(remember to add your API key!)

// information to reach API


const dataMuseUrl =
'https://api.datamuse.com/words?';
const queryParams = 'rel_jjb=';

// selecting page elements


const inputField =
document.querySelector('#input');
const submit = document.querySelector('#submit');
const responseField =
document.querySelector('#responseField');

// AJAX function
const getSuggestions = () => {
const wordQuery = inputField.value;
const endPoint = dataMuseUrl + queryParams +
wordQuery;

const xhr = new XMLHttpRequest();


xhr.responseType = 'json';

xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
renderWordResponse(xhr.response);
}
};
xhr.open('GET', endPoint);
xhr.send();
}

// clear previous results and display results to


webpage
const displaySuggestions = (event) => {
event.preventDefault();
while(responseField.firstChild){
responseField.removeChild(responseField.firstChild);
};
getSuggestions();
};

submit.addEventListener('click', displaySuggestions);

// information to reach Rebrandly API


const apiKey = '<Your API Key>';
const rebrandlyUrl =
'https://api.rebrandly.com/v1/links';

// element selector
const shortenButton =
document.querySelector('#shorten');

// AJAX functions
const shortenUrl = () => {
const urlToShorten = inputField.value;
const data = JSON.stringify({destination:
urlToShorten});

const xhr = new XMLHttpRequest();


xhr.responseType = 'json';

xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
renderByteResponse(xhr.response);
}
};
xhr.open('POST', rebrandlyUrl);
xhr.setRequestHeader('Content-type',
'application/json');
xhr.setRequestHeader('apikey', apiKey);
xhr.send(data);
}

// Clear page and call AJAX functions


const displayShortUrl = (event) => {
event.preventDefault();
while(responseField.firstChild){

responseField.removeChild(responseField.firstChild);
};
shortenUrl();
};

shortenButton.addEventListener('click',
displayShortUrl);
// wordSmith helperFunctions are on lines 4 - 50
// byteSize helperFunctions are on lines 52 - 76

// Formats Response to look presentable on


webpage
const renderWordResponse = (res) => {
// Handles if res is falsey
if(!res){
console.log(res.status);
}
// In case res comes back as a blank array
if(!res.length){
responseField.innerHTML = "<p>Try
again!</p><p>There were no suggestions
found!</p>";
return;
}

// Creates an array to contain the HTML strings


let wordList = []
// Loops through the response and maxxing out at
10
for(let i = 0; i < Math.min(res.length, 10); i++){
// Creates a list of words
wordList.push(`<li>${res[i].word}</li>`);
}
// Joins the array of HTML strings into one string
wordList = wordList.join("");

// Manipulates responseField to render the


modified response
responseField.innerHTML = `<p>You might be
interested in:</p><ol>${wordList}</ol>`;
return;
}

// Renders response before it is modified


const renderRawWordResponse = (res) => {
// Takes the first 10 words from res
let trimmedResponse = res.slice(0, 10);
// Manipulates responseField to render the
unformatted response
responseField.innerHTML =
`<text>${JSON.stringify(trimmedResponse)}</text>`;
}

// Renders the JSON that was returned when the


Promise from fetch resolves.
const renderJsonWordResponse = (res) => {
// Creating an empty object to store the JSON in
key-value pairs
let rawJson = {};
for(let key in response){
rawJson[key] = response[key];
}
// Converting JSON into a string and adding line
breaks to make it easier to read
rawJson = JSON.stringify(rawJson).replace(/,/g, ",
\n");
// Manipulates responseField to show the returned
JSON.
responseField.innerHTML =
`<pre>${rawJson}</pre>`;
}

// Manipulates responseField to render a formatted


and appropriate message
const renderByteResponse = (res) => {
if(res.errors){
// Will change the HTML to show this error
message if the response had an error
responseField.innerHTML = "<p>Sorry, couldn't
format your URL.</p><p>Try again.</p>";
} else {
// If there was no error, then the HTML will show
this message
responseField.innerHTML = `<p>Your shortened
url is: </p><p> ${res.shortUrl} </p>`;
}
}

// Manipulates responseField to render an


unformatted response
const renderRawByteResponse = (res) => {
if(res.errors){
// Changes the HTML to show this error message
if the response had an error
responseField.innerHTML = "<p>Sorry, couldn't
format your URL.</p><p>Try again.</p>";
} else {
// Changes the HTML to show this raw response if
there was no error
// Formats the response into a more organized
structure
let structuredRes =
JSON.stringify(res).replace(/,/g, ", \n");
structuredRes = `<pre>${structuredRes}</pre>`;

responseField.innerHTML = `${structuredRes}`;
}
}


JavaScript é a linguagem da web por causa de seus recursos assíncronos. AJAX, que significa JavaScript
assíncrono e XML, é um conjunto de ferramentas que são usadas juntas para aproveitar os recursos assíncronos do
JavaScript.
 Existem muitos métodos de solicitação HTTP, dois dos quais são GET e POST.
 Solicitações GET solicitam apenas informações de outras fontes.
 Os métodos POST podem introduzir novas informações para outras fontes, além de solicitá-las.
 Pedidos GET podem ser escritos usando um objeto XMLHttpRequest e JavaScript baunilha.
 Solicitações POST também podem ser escritas usando um objeto XMLHttpRequest e JavaScript baunilha.
 Escrever solicitações GET e POST com objetos XHR e baunilha JavaScript requer a construção do objeto XHR
usando new, definindo responseType, criando uma função que manipulará o objeto de resposta e abrindo e
enviando a solicitação.
 Para adicionar uma string de consulta a um endpoint de URL, você pode usar ?e incluir um parâmetro.
 Para fornecer parâmetros adicionais, use &e inclua um par de valores-chave, associado por =.
 Determinar como escrever corretamente as solicitações e como implementá-las corretamente requer ler
atentamente a documentação da API com a qual você está trabalhando.
1. As solicitações GET e POST podem ser criadas de várias formas.
2. Use AJAX para solicitar dados de forma assíncrona de APIs. fetch()e async/ awaitsão novas
funcionalidades desenvolvidas em ES6 (promessas) e ES8 respectivamente.
3. Promessas são um novo tipo de objeto JavaScript que representa dados que serão retornados de
uma solicitação.
4. fetch()é uma API da web que pode ser usada para criar solicitações. fetch()irá retornar
promessas.
5. Podemos encadear .then()métodos para lidar com promessas retornadas por fetch().
6. O .json()método converte uma promessa retornada em um objeto JSON.
7. async é uma palavra-chave usada para criar funções que retornarão promessas.
8. await é uma palavra-chave que é usada para dizer a um programa para continuar se movendo
pela fila de mensagens enquanto uma promessa é resolvida.
9. awaitsó pode ser usado dentro de funções declaradas com async.

Você também pode gostar