fetch
함수는 HTTP response 객체를 래핑한 Promise 객체를 반환한다.
fetch 함수가 반환한 Promise 객체
Response {
__proto__: Response {
type: 'basic',
url: '<https://jsonplaceholder.typicode.com/posts/1>',
redirected: false,
status: 200,
ok: true,
statusText: '',
headers: Headers {},
body: ReadableStream {},
bodyUsed: false,
arrayBuffer: ƒ arrayBuffer(),
blob: ƒ blob(),
clone: ƒ clone(),
formData: ƒ formData(),
json: ƒ json(),
text: ƒ text(),
constructor: ƒ Response()
}
}
fetch 함수에는 HTTP 요청을 전송할 URL, HTTP 요청 메서드, HTTP 요청 헤더, 페이로드 등을 설정한 객체를 전달한다.
fetch("<https://jsonplaceholder.typicode.com/posts/1>")
.then((response) => response.json())
.then((data) => console.log(data))
→ 단순히 원격 API에 있는 데이터를 가져올 때 쓰임→ fetch함수는 디폴트로 GET 방식으로 작동하고, 옵션 인자가 필요 없음.
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit↵suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto"
}
→ 응답(response) 객체는 json() 메서드를 제공하고, 이 메서드를 호출하면 응답(response) 객체로부터 JSON 형태의 데이터를 자바스크립트 객체로 변환하여 얻을 수 있음.
fetch("<https://jsonplaceholder.typicode.com/posts>", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test",
body: "I am testing!",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
→ 폼 등을 사용해서 데이터를 만들어 낼 때, 보내는 데이터의 양이 많거나, 비밀번호 등 개인정보를 보낼 때 POST 메서드 사용→ 새로운 포스트 생성 위해서는 method 옵션을 POST로 지정해주고, headers 옵션으로 JSON 포맷 사용한다고 알려줘야 함. body 옵션에는 요청 전문을 JSON 포맷으로 넣어줌.→ headers에서 json 형식임을 알려주지 않으면 서버에서 못 읽는 문제가 (종종?) 생겼음.
{title: "Test", body: "I am testing!", userId: 1, id: 101}
fetch("<https://jsonplaceholder.typicode.com/posts>", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test",
body: "I am testing!",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
→ API에서 관리하는 데이터의 수정을 위해 PUT 메서드 사용함.→ method 옵션만 PUT으로 설정한다는 점 빼놓고는 POST 방식과 비슷
fetch("<https://jsonplaceholder.typicode.com/posts/1>", {
method: "DELETE",
})
.then((response) => response.json())
.then((data) => console.log(data))