javascript fetch

fetch 를 통해서 URL의 데이터를 받는 방식은 여러 방식이 존재할 수 있다.

기본적인 방식으로는 fetch 란 것이 promise 가 내재되어있기때문에
then을 통해서 비동기를 순차적으로 실행할수 있고

1
2
3
4
5
fetch(URL)
.then(res => res.json()) //1번 순서
.then(data => { console.log() } //2번 순서 res.json
.then((e) => { data.response.docs } //2번 순서

물론 asnyc 방식으로 순서를 지정하는 것도 가능하다

1
2
3
4
5
const fetchFunc = async () => {
const res = await fetch(url);
data = await res.json();
data2 = await data.response.docs;
}

아직까지 몇번 써보지 않아서 그렇지만 ajax보다 매우 편리하다!

1
2
3
4
5
6
7
8
let response = await fetch(url);

if (response.ok) { // HTTP 상태 코드가 200~299일 경우
// 응답 몬문을 받습니다(관련 메서드는 아래에서 설명).
let json = await response.json();
} else {
alert("HTTP-Error: " + response.status);
}

HTTP 스테이터스 파악도 간단해서 실질적으로 접속 확인 다중체크 등에 매우 자주 써볼 생각이다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
async function postData(url = '', data = {}) {
// 옵션 기본 값은 *로 강조
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE 등
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data), // body의 데이터 유형은 반드시 "Content-Type" 헤더와 일치해야 함
});
return response.json(); // JSON 응답을 네이티브 JavaScript 객체로 파싱
}

postData('https://example.com/answer', { answer: 42 }).then((data) => {
console.log(data); // JSON 데이터가 `data.json()` 호출에 의해 파싱됨
});

기본적인 URL쿼리를 통한 get 방식은 한계가 있기에 ajax와 마찬가지로 post 방식도 지원한다.
물론 POST방식을 테스트해보니 역시 CORS문제가 나와서 서버관련 문제라 예전에 해결해본 경험이 있으나
까먹었으니 다시한번 해결방법에 대해 정리를 해볼려고 한다