fetch('https://jonghyeon.com/todos')
.then((res) => {
return res.json();
})
.then((todos) => {
// todos 조회 완료!
console.log(todos);
});
Response에는 text, json 외에도 아래와 같은 method들이 있습니다.
Response.arrayBuffer()
Response.blob()
Response.clone()
Response.error()
Response.formData()
Response.json()
Response.redirect()
Response.text()
fetch는 HTTP error가 발생하더라도 reject 되지 않습니다.
네트워크 에러나 요청이 완료되지 못한 경우에만 reject 됩니다.
그러므로 서버 요청 중 에러가 생겼을 경우에도 then으로 떨어지므로 response의 status code나 ok를 체크해주는 것이 좋습니다.
res.ok는 status가 200~299 사이인 경우 true가 됩니다.
fetch('https://jonghyeon.com/todos-undefined-api')
.then((res) => {
if (res.ok) {
// 이 구문이 있어야 서버 요청 중 에러가 생겼을 경우를 체킹할 수 없다.
return res.json();
} else {
throw new Error('요청이 처리되지 못함');
}
})
.then((result) => console.log(result))
.catch((e) => alert(e.message));
const headers = new Headers();
headers.append('x-auth-token', 'TOKEN');
fetch('https://jonghyeon.com/product', {
method: 'POST',
headers,
body: JSON.stringify(product),
});