fetch
- 비동기 http 요청을 더 편하게 쓸 수 있는 API.
- XMLHTTPRequest보다 최신 브라우저 요구사항에 맞게 다양한 기능을 제공함.
- fectch의 기본 응답 결과는 Response 객체임.
fetch('api주소 입력')
.then(res -> {
return res.json() //res.text()로 요청할 경우 응답이 text로 전달됨.
})
.then(todos => {
//todos 조회완료
console.log(todos) //text요청시 JSON.parse(data)를 해줘야 함.
})
res.text()
: 응답이 text로 전달됨. Response 객체를 얻은 뒤엔 응답을 JSON.parse(data)
등으로 처리해야 함.
res.blob()
: 이미지 url을 fetch로 가져오면 불려진 이미지 data를 url로 바꿔서 사용할 수 있음. URL.createObjectURL()
로 URL 형식으로 표현할 수 있음.
const $image = document.createElement('img');
const imageURL = 'https://indistreet.com/_next/iamge?'
fetch(imageURL)
.then(res => {
return res.blob();
})
.then(data => {
const url = URL.createObjectURL(data);
$image.src = url
document.querySelector('body').appendChild($image)
})
error 잡기
- HTTP error가 발생하더라도 reject되지 않음. 네트워크 에러나 요청이 완료되지 못한 경우만 reject됨 → response의 status code나 ok를 체크해주는 것이 좋음.
fetch('이상한 url')
.then(res => {
if(res.ok) {
return res.json();
}
throw new Error('요청 처리 실패');
})
.then(result => {
console.log(result);
})
.catch(e => console.log(e.messgae));
- 유효하지 않은 Not found api를 JSON.parse()를 하려고 해서 에러가 나는 것임.
처리를 안했을 경우 나타나는 error.- throw error를 통해 에러 메시지를 받을 수 있음.
- res.ok는 status가 200대인 경우만 true임. 300대도 false가 나올 수 있음을 유의하자.
- fetch의 두 번째 인자로 옵션을 줄 수 있음.
const headers = new Headers();
headers.append('x-auth-token', 'TOKEN');
fetch('url') , {
method : 'POST',
headers,
body: JSON.stringify(product)
}