서버로 네트워크 요청을 보내고 응답을 받을 수 있도록 하는 Method.
백엔드 서버와 비동기 요청을 진행한다.
fetch('url',
{method: '~',
headers : {"Context-Type" : "~"},
body: ~,
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log(error));
만약 fetch 함수 이후에 작성된 어떠한 코드가 있고, 그것이 response가 도착하기 전에 실행될 수 있다면 실행된다.
이를테면..
console.log('start');
fetch(~);
console.log('End');
console.log('start') -> fetch() -> console.log('end') -> fetch response 처리(callback 함수 실행)
과 같이 실행되는 것이다.
만약 동기적으로 실행됐다면 response가 올 때까지 console.log('end')는 실행이 되지 않았을 것.
- 'URL' : 접근하고자하는 웹 페이지의 주소
- fetch( 'url', {~....}) : options.
A. method : 동작을 지정한다. GET / POST / PUT / DELETE / PATCH
B. headers : HTTP 요청 헤더.
=> Context-Type은 데이터가 어떤 타입인지를 나타낸다.
C. body : 전달하고자 하는 것. 객체로 작성해야한다.- Response
- response.text() || json().
- 차이는 자바스크립트 객체로 바꾸냐 바꾸지 않느냐.
- json()으로 받아오면 이후 JSON.parse()를 쓸 필요가 없다.
- response.status
- 응답의 HTTP 코드. 200, 404 등등이 있는데... 다른 POST에서 정리.
기본 골조는 위 처럼 작성되며 fetch는 Promise 객체를 반환한다.
Promise 객체
- 비동기 작업의 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.
fetch('url')
.then((response)=>response.json())
.then((result)=>{console.log(result);});
fetch('url',
{ method : 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body:JSON.stringify(variable)
})
.then((response)=>response.text())
.then((result)=>{console.log(result);});
JSON.stringify : 전달하는 데이터를 JSON으로 변환한다. Serialization.
JSON.parse : 전달받은 JSON 객체를 js의 값이나 객체로 변환한다.
fetch('url',
{ method : 'PUT',
body:JSON.stringify(variable)
})
.then((response)=>response.text())
.then((result)=>{console.log(result);});
fetch('url',
{ method : 'DELETE'
})
.then((response)=>response.text())
.then((result)=>{console.log(result);});
fetch('url',
{ method : 'PATCH',
body:JSON.stringify(variable)})
.then((response)=>response.text())
.then((result)=>{console.log(result);});
✖ 보통 GET과 POST를 활용하는 것 같다. PUT과 DELETE는 자칫 전체 데이터를 건드릴 가능성이 있어서.. 였던 것 같은데
fetch 함수는 서버에 Request를 보내고, Response를 받기 위한 함수.
- HEAD / BODY 로 나뉜다.
- HEAD : Request에 대한 부가 정보. Method, Path, Authority 등등.
- Method
- GET(조회) / POST(전달) / PUT(덮어쓰기) / DELETE(삭제) / PATCH(변경)
- BODY : 실제 데이터를 담는 부분
- POST, PUT, PATCH
fetch와 연결되는 것이 REST API와 AJAX가 있으며, 다른 POST에 정리합니다.