코딩 관련/Javascript와 jQuery, JSON
[JavaScript] fetch 사용법, fetch 응답 사용
메리짱123
2021. 6. 23. 14:53
반응형
fetch 사용해보기
fetch() 기본
//fetch를 호출하면 브라우저는 네트워크 요청을 보내고 promise를 반환한다.
let promise = fetch(url, {options})
fetch(url, options)
//api호출 성공 시 응답(response) 반환
.then((response) => console.log("response:", response))
//실패시 error 반환
.catch((error) => console.log("error:", error));
fetch 사용 예시
fetch("https://localhost:8080/urlurl", {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
referrer: 'no-referrer',
body: JSON.stringify(obj),
})//fetch 실행이 끝나면 then의 내용 실행
//응답을 JSON 형태로 파싱한다
.then(response => response.json())
.then(function (res){
})
응답을 처리할 때 사용하는 메서드
response.text() | 응답을 읽고 텍스트를 반환 |
response.json() | 응답을 JSON 형태로 파싱 |
response.formData() | 응답을 FormData 객체 형태로 반환 |
response.blob() | 응답을 Blob(타입이 있는 바이너리 데이터) 형태로 반환 |
response.arrayBuffer() | 응답을 ArrayBuffer(바이너리 데이터를 로우 레벨 형식으로 표현한 것) 형태로 반환 |
* 본문을 읽을 때 사용되는 메서드는 딱 하나만 사용할 수 있다.
let text = await response.text(); // 응답 본문을 읽고 test를 반환
let parsed = await response.json(); // 실패
반응형