const promise = fetch(url, [, options])
fetch('<https://jsonplaceholder.typicode.com/todos/1>')
.then(response => console.log(response));
//첫 번째 인수로 HTTP 요청을 전송할 URL만 전달하여 GET 요청을 전송
Response.prototype에는 Response 객체에 포함되어 있는 HTTP 응답 몸체를 위한 다양한 메서드를 제공 한다
fetch 함수에 첫 번째 인수로 HTTP 요청을 전송할 URL 두번째 인수로 HTTP 요청 메서드, HTTP 요청 헤더, 페이로드 등을 설정한 객체를 전달
const request = {
get(url) {
return fetch(url);
},
post(url, payload) {
return fetch(url, {
method: 'POST',
headers: { 'content-Type': 'application/json' },
body: JSON.stringify(payload)
});
},
patch(url, payload) {
return fetch(url, {
method: 'PATCH',
headers: { 'content-Type': 'application/json' },
body: JSON.stringify(payload)
});
},
delete(url) {
return fetch(url, { method: 'DELETE' });
}
};
request.get('<https://jsonplaceholer.typicode.com/todos/1>')
.then(response => response.json())
.then(todos => console.log(todos))
.catch(err => console.log(err))
request.post('<https://jsonplaceholder.typicode.com/todos>', {
userId: 1,
title: 'JavaScript',
completed: false
}).then(response => response.json())
.then(todos => console.log(todos))
.catch(err => console.log(err))