Programming/Javascript
[JavaScript] Fetch API
JIHYEON LEE
2021. 12. 29. 21:53
Fetch API
javascript에서 비동기 HTTP 요청을 보내는 방법
jQuery를 사용하지 않는 추세라 fetch를 많이 사용함
형식: fetch(url, [options/method, headers, ...])
Fetch API를 사용해서 비동기 HTTP 요청 보내기
1. GET 요청
function addBookmark(movie_id) {
fetch("/movie/addBookmark?movie_id=" + movie_id)
.then(response => response.text())
.then(response => {
if(response == "success") {
location.reload();
} else {
alert("My List 추가에 실패하였습니다.");
}
});
}
2. POST 요청
let submit = () => {
let input = document.getElementById('input');
let target = document.getElementById('title');
fetch('/title', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ 'title': input.value }),
})
.then(res => res.json())
.then(json => target.innerHTML = json.title)
.catch(error => console.error('Error: ', error));
}
3. 회신 값
text() : text로 반환
json() : json 형태로 반환
formData() : formData 객체 형태로 반환
blob() : Blob 형태로 반환
arrayBuffer() : ArrayBuffer 형태로 반환
body() : 응답 본문을 청크 단위로 읽을 수 있음
4. async와 await
비동기적으로 동작하는 fetch에서 순서를 보장받기 위해 사용
await은 async 선언이 된 함수 안에서만 사용 가능
async 선언이 된 함수는 반드시 Promise를 return함
순서를 보장 받을 수 있기 때문에 디버깅, 예외처리에 용이
let submit = async () => {
let input = document.getElementById('input');
let target = document.getElementById('title');
let replaceTitle = json => target.innerHTML = json.title;
let url = '/title'
let options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({'title': input.value}),
}
try {
let response = await fetch(url, options);
let json = await response.json();
let task = await replaceTitle(json);
} catch (err) {
console.log(err);
}
}
reference
- Fetch API
https://velog.io/@prayme/Fetch-API
- fetch