*Fetch ๋?
- Ajax๋ฅผ ๊ตฌํํ ์ ์๋ ๋น๊ต์ ์ต๊ทผ์ ๋์จ ๊ธฐ์ .
- jQuery.ajax()์ ๋ค๋ฅธ์ ์ (1) fetch๋ก๋ถํฐ ๋ฐํ๋๋ ๊ฐ์ฒด๋ HTTP error์ํ๋ฅผ rejectํ์ง ์๋๋ค. (2) ์ฟ ํค๋ฅผ ๋ณด๋ด๊ฑฐ๋ ๋ฐ์ง ์๋๋ค๋์ .
- ์นํ์ด์ง ์ ์ฒด๋ฅผ ๋ฆฌ๋ก๋ฉ(re-loading)ํ์ง ์๊ณ , ์ผ๋ถ๋ถ๋ง ๋ค๋ฅธ ๋ฐ์ดํฐ๋ก ๊ต์ฒด(๊ฐฑ์ )ํ๋ ๊ธฐ๋ฅ์ ํ๋ค.
- Promise ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ ๋น๋๊ธฐ ํต์ ์ ํ๋ค.
*๋น๋๊ธฐ ์ฒ๋ฆฌ : ์ผ๋ฐ์ ์ผ๋ก ์ด๋ ํ ํน์ ๋ช
๋ น์ด๊ฐ ์์ผ๋ฉด, ๊ทธ๊ฒ์ด ์๋ฃ๋ ํ์ ๋ค์ ๋ช
๋ น์ด๋ฅผ ์ํํ์ง๋ง, ๋น๋๊ธฐ์ฒ๋ฆฌ๋ ํน์ ์ฝ๋๋ฅผ ์คํํ๊ณ , ๊ทธ ์ฝ๋๊ฐ ์๋ฃ๋๊ธฐ ์ ์ ๋ค์์ฝ๋๋ฅผ ์ด์ด์ ์ํํ๋๊ฒ์ ๋งํ๋ค.
*Promise(ํ๋ก๋ฏธ์ค) : ์๋ฐ์คํฌ๋ฆฝํธ์์ ๋น๋๊ธฐ ์ฒ๋ฆฌ์ ํ์ฉ๋๋ ๊ฐ์ฒด๋ฅผ ๋งํ๋ค.
*Fetch ๊ฐ๋จํ ์์ (1)
์ต์ปค(<a>ํ๊ทธ) ๋ฅผ ๊ฑธ์ด๋๊ณ , ์ด๋ฅผ ํด๋ฆญํ๊ฒ๋๋ฉด fetch๋ฅผ ํตํด ๋ค๋ฅธ ํ์ผ์ ๋ถ๋ฌ์ ํ๋ฉด์ ๋ํ๋๋๋ก ํ๋ ์์ .
*ํ์ผ๊ตฌ์ฑ
home.html
spring.txt
*Fetch ํจ์
function fetchPage(fileName){
fetch(fileName).then(function(response){
response.text().then(function(text){
document.querySelector('#text').innerHTML = text;
})})};
*spring.txt
*home.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>fetch example</h1>
<h2> season </h2>
<ol>
<li> <a href="#!spring" onclick="fetchPage('spring.txt')">spring </a> </li>
<li>summer</li>
<li>fall</li>
<li>winter</li>
</ol>
<p id="text"></p>
<script type="text/javascript">
function fetchPage(fileName){
fetch(fileName).then(function(response){
response.text().then(function(text){
document.querySelector('#text').innerHTML = text;
})})};
</script>
</body>
</html>
*๊ฒฐ๊ณผํ๋ฉด
*Fetch ์ ๊ธฐ๋ณธ ์ฝ๋์ ์ต์
๋ค
*๊ธฐ๋ณธ์ ์ธ fetch ์ฝ๋(์ถ์ฒ : mozilla)
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
๊ธฐ๋ณธ์ ์ผ๋ก fetch๋ ํด๋น url์ ์ ๋ณด๋ฅผ ์์ฒญํ๋ค.
Fetch์ ๋ชจ๋ ์ต์
๋ค
// Example POST method implementation:
postData('http://example.com/answer', {answer: 42})
.then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
.catch(error => console.error(error));
function postData(url = '', data = {}) {
// Default options are marked with *
return fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
.then(response => response.json()); // parses JSON response into native JavaScript objects
}