fetch() 란?
-원격 API를 간편하게 호출할 수 있도록 브라우저에서 제공하는 함수
-자바스크립트를 사용하면 필요할 때 서버에 네트워크 요청을 보내고 새로운 정보를 받
아오는 일을 할 수 있다.
-HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작
할 수 있는 인터페이스를 제공
요청하는 것 : get/post/put/delete
-get : 데이터 받기
-post : 데이터 생성
-put : 데이터 수정
-delete : 데이터 삭제
fetch(url, options)
.then((response) => console.log("response:", response))
.catch((error) => console.log("error:", error));
//예제 1
let result = fetch(serverURL);
result
.fetch(response => {
if(response.ok) {
//요청 성공
}
})
.catch(error => {
// 요청 실패
})
//예제 2 - async/await
let url = 'https://api.github.com/repos/javascript-tutorial/ko.javascript.info/com
mits';
let response = await fetch(url);
let commits = await response.json(); // 응답 본문을 읽고 JSON 형태로 파싱함
alert(commits[0].author.login);
//예제 3 - promise
fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commit
s')
.then(response => response.json())
.then(commits => alert(commits[0].author.login));
-http 활용이 가능
-기존 XMLHTTPRequest를 대체하는 HTTP 요청 API
-Promise를 리턴하도록 정의됨
-네트워크 요청 성공 시 Promise는 REsponse 객체를 resolve, 실패시 reject
let result = fetch(serverURL)
result
.then(response => {
if(response.ok){
//요청 성공 .ok는 확인 메서드
}
})
.catch(error =>{
//요청 실패
})
fetch(serverURL)
.then(response => {
response.ok
response.status
response.statusText
response.url
response.bodyUsed
})
-Response 객체는 결과에 대한 다양한 정보를 담는다.
-.ok : HTTP Status code가 200-299 사이면 true, 그 외 false이다.
-.status : HTTP status code를 담는다
-.url : 요청한 url정보를 담는다.
fetch(serverURL)
.then(resp => {
for (let [k, y] of resp.headers) {
console.log(k, v)
}
})
-response.headers : response 객체의 헤더 정보를 얻을 수 있다.
fetch(serverURL)
.then(response => {
return response.json()
})
.then(json => {
console.log('body : ', json)
})
-response.json() 메서드는 얻어온 body 정보를 json으로 만드는 Promise를 반환한다.
-promise가 resolve 되면 얻어온 body 정보를 읽는다.
-response.text(), resopnse.blob(), response.formData() 등의 메서드로 다른 형태의 바디를 읽는다.
fetch(serverURL, {
method: 'post',
//2)get, post, put, patch, delete 등 메서드 필드로 여러 요청 메서드 활용가능
headrer: {
'Content-Type':'application/json;charset=utf-8',
Authentication: 'mysecret'
},
//1)fetch 메서드 옵션 : url
//3)header 정보 넣을 수 있음
body: JSON.stringify(formData)
//1)fetch 메서드 옵션 : options
//3)body 정보 넣을 수 있음
})
.then(response => {
return response.json()
})
.then(json => {
console.log('POST 요청 결과:', json)
})
1)fetch(url, options)로 fetch 메서드 옵션을 넣는다.
2)method 필드로 여러 요청 메서드를 활용한다.
3)headers, body 필드를 활용해 서버에 추가 정보를 보낸다.