javascript를 사용하면 필요할 때 서버에 네트워크 요청을 보내고 새로운 정보를 받아올수 있음
이때, 페이지를 새로고침 없이 조회 가능
fetch()는 구식 브라우저에서는 지원하지 않지만, 대부분의 모던 브라우저에서 지원 됨
* 기본문법
let promise = fetch(url, [options])
- url : 접근 하고자 하는 URL
- options : 선택 항목, method나 header등을 지정 할 수 있음
- options에 아무것도 넘기지 않으면 GET 으로 요청
- fetch()를 호출하면 브라우저는 네트워크 요청을 보내고 promise 가 반환됨
- http 상태는 응답 프로퍼티를 사용하여 확인 가능
- status : http 상태코드
- ok : http 상태코드가 200 ~ 299 사이일 경우 true, boolean
let response = await fetch(url);
if (response.ok){
let json = await response.json();
}else{
console.log("Http-Error : " + response.status);
}
* respons
- 프라미스를 기반으로 하는 다양한 메서드가 존재
- response.text() : 응답을 텍스트로 반환
- response.json() : 응답을 json 형태로 파싱
- response.formData() : 응답을 FormData 객체 형태로 반환
- response.blob() : 응답을 Blob 형태로 반환
- response.arrayBuffer() : 응답을 ArrayBuffer 형태로 변환
- response.body : 응답본문을 청크 단위로 읽을 수 있음
* GitHub에서 마지막 커밋을 JSON 객체 형태로 받음..
let url = 'https://api.github.com/repos/javascript-tutorial/ko.javascript.info/commits';
let response = await fetch(url);
let commits = await response.json(); // 응답 본문을 읽고 JSON 형태로 파싱함 console.log(commits[0].author.login);
* 위 예시를 wait 없이 프라미스만 사용하면 다음과 같이
fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits')
.then(response => response.json())
.then(commits => console.log(commits[0].author.login));
* POST 요청 시 주의할 점은 본문이 문자열일때 Content-Type 헤더가 text/plain;charset=UTF-8 이 기본 설정
* json 형태로 보낼려면 headers의 Content-Type을 application/json;charset=utf-8 으로 설정 해야 함
'WEB front-end > Javascript' 카테고리의 다른 글
Set (0) | 2022.06.21 |
---|---|
Map (0) | 2022.06.20 |
예외처리... (0) | 2022.06.02 |
async/await (0) | 2022.05.27 |
promise (0) | 2022.05.27 |
댓글