Requests 2
브라우저의 fetch객체를 이용해 서버에 요청을 보내는 방법을 정리하였습니다.
< Introduction to Requests with ES6 >
AJAX하면 예전에는 XMLHttpRequest(XHR) API를 이용하는 것이 일반적이었으며, 그리고 불편함을 느낀 사람들이 jQuery를 통해 AJAX를 구현하기 시작했고 그 이후로 Fetch API가 ES6(ES2015) 표준으로 등장하면서 이제는 일반적으로 Fetch API를 통해 구현하는 것이 일반적이 되었습니다.
Fetch API는 비동기 처리를 구현하기 위해 Promises를 이용하고, 반환값으로 Promise를 가집니다.
Fetch API는 브라우저에서 바로 사용 가능합니다.(Fetch is Web API)
Reference : MDN - Fetch API
Fetch API - Web APIs | MDN
The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.
developer.mozilla.org
< fetch() GET Requests >
< The fetch() function : >
- Creates a request object that contains relevant information that an API needs.
: ex) req.params- Sends that request object to the API endpoint provided.
- Returns a promise that ultimately resolves to a response object, which contains the status of the promise with information the API sent back.
: A fetch() call is only rejected if the network request itself fails for some reason (host not found, no connection, server not responding, etc...).
Any result back from the server (404, 500, etc...) is considered a successful request from the promise point of view.
< Fetch( ) GET Requests : Boilerplate Code >

: The .json() method converts a returned promise to a JSON object.
(for detail : It returns a promise which resolves with the result of parsing the body text as JSON)
Example)
fetch('https://api-to-call.com/endpoint')
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed!')
}, networkError => console.log(networkError.message))
.then(jsonResponse => {
return jsonResponse;
})
Example in practice : Use Datamuse API
// Information to reach API
const url = 'https://api.datamuse.com/words';
const queryParams = '?sl=';
// Selects 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 = `${url}${queryParams}${wordQuery}`;
fetch(endpoint, {cache: 'no-cache'}).then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message)
})
.then(jsonResponse => {
renderResponse(jsonResponse);
})
}
// Clears previous results and display results to webpage
const displaySuggestions = (event) => {
event.preventDefault();
while(responseField.firstChild){
responseField.removeChild(responseField.firstChild);
}
getSuggestions();
};
submit.addEventListener('click', displaySuggestions);
< fetch() POST Requests >
< Fetch( ) POST Requests : Boilerplate Code >

Notice that the initial call takes two arguments :
- an endpoint and an object that contains information needed for the POST request. The rest of the request is identical to the GET request.
Example)
fetch('https://api-to-call.com/endpoint', {
method: 'POST',
body: JSON.stringify({id: '200'})
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed!');
}, networkError => console.log(networkError.message))
.then(jsonResponse => {
return jsonResponse;
})
Example in practice : Use Rebrandly API
// Information to reach API
const apiKey = '<input your api key>';
const url = 'https://api.rebrandly.com/v1/links';
// Some page elements
const inputField = document.querySelector('#input');
const shortenButton = document.querySelector('#shorten');
const responseField = document.querySelector('#responseField');
// AJAX functions
const shortenUrl = () => {
const urlToShorten = inputField.value;
const data = JSON.stringify({destination: urlToShorten});
fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json',
'apikey': apiKey
},
body: data
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed!');
}, networkError => console.log(networkError.message))
.then(jsonResponse => {
renderResponse(jsonResponse);
})
}
// Clear page and call AJAX functions
const displayShortUrl = (event) => {
event.preventDefault();
while(responseField.firstChild){
responseField.removeChild(responseField.firstChild)
}
shortenUrl();
}
shortenButton.addEventListener('click', displayShortUrl);
< async GET Requests >
To make it easier to use fetch() Using the async...await syntax as well as try and catch statements.
< async GET Requests : Boilerplate Code >

: Since .json( ) is an asynchronous method we have to await until the promise status is resolved.
Example)
const getData = async () => {
try {
const response = await fetch('https://api-to-call.com/endpoint');
if (response.ok) {
const jsonResponse = await response.json();
return jsonResponse;
}
throw new Error('Request failed!');
} catch(error) {
console.log(error);
}
}
Example in practice : Use Datamuse API
// Information to reach API
const url = 'https://api.datamuse.com/words?';
const queryParams = 'rel_jja=';
// Selecting page elements
const inputField = document.querySelector('#input');
const submit = document.querySelector('#submit');
const responseField = document.querySelector('#responseField');
// AJAX function
// Code goes here
const getSuggestions = async () => {
const wordQuery = inputField.value;
const endpoint = `${url}${queryParams}${wordQuery}`;
try {
const response = await fetch(endpoint, {cache: 'no-cache'})
if (response.ok) {
const jsonResponse = await response.json();
renderResponse(jsonResponse)
}
} catch(error) {
console.log(error);
}
}
// 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);
< async POST Requests >
< async POST Requests : Boilerplate Code >

: As with the other GET and POST requests that you’ve been making, an async POST request requires more information : an object that contains information needed for the POST request.
Example)
const getData = async() => {
try {
const response = await fetch('https://api-to-call.com/endpoint', {
method: 'POST',
body: JSON.stringify({id: 200})
})
if (response.ok) {
const jsonResponse = await response.json();
return jsonResponse;
}
throw new Error('Request failed!');
} catch(error) {
console.log(error);
}
}
Example in practice : Use Rebrandly API
// information to reach API
const apiKey = 'e8ffafa382814e839f44eb49ebd47c45';
const url = 'https://api.rebrandly.com/v1/links';
// Some page elements
const inputField = document.querySelector('#input');
const shortenButton = document.querySelector('#shorten');
const responseField = document.querySelector('#responseField');
// AJAX functions
// Code goes here
const shortenUrl = async() => {
const urlToShorten = inputField.value;
const data = JSON.stringify({destination: urlToShorten});
try {
const response = await fetch(url, {
method: 'POST',
body: data,
headers: {
'Content-type': 'application/json',
'apikey': apiKey
}
})
if (response.ok) {
const jsonResponse = await response.json();
renderResponse(jsonResponse);
}
} catch(error) {
console.log(error);
}
}
// Clear page and call AJAX functions
const displayShortUrl = (event) => {
event.preventDefault();
while(responseField.firstChild){
responseField.removeChild(responseField.firstChild);
}
shortenUrl();
}
shortenButton.addEventListener('click', displayShortUrl);
Reference : Fetching data From Server(Using XHR, Fetch
Fetching data from the server - Learn web development | MDN
This article shows how to start working with both XHR and Fetch to fetch data from the server.
developer.mozilla.org
Reference : Use Fetching
Using Fetch - Web APIs | MDN
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across th
developer.mozilla.org
Reference : Third-Party APIs
Third-party APIs - Learn web development | MDN
This article has given you a useful introduction to using third-party APIs to add functionality to your websites.
developer.mozilla.org