자바스크립트로 실제 http 요청을 해보려고 한다.
XHR은 XMLHttpRequest 의 약자이다.
예전에는 이런 구문을 사용해서 자바스크립트에서 http 요청을 보냈다.
const req = new XMLHttpRequest();
req.onload = function () {
console.log("LOAD");
const data = JSON.parse(this.responseText);
};
req.onerror = function () {
console.log("ERROR");
}
req.open("GET", "https://swapi.dev/api/people/1");
req.send();
성공일때 onload 콜백에서는 성공메시지를
바로 사용은 못하고 파싱해줘야한다.
실패일때 onerroe 콜백에서는 실패메시지를 띄운다
open 으로 get 요청하면 URL을 가져와서 연 다음 전송한다.
사실 이거보다 작성할 코드는 훨씬 많다.
좀 더 간편하게 사용할 수 있는 함수가 있는데
바로 fetch 이다.
일단 URL을 전송하면 기본적으로 GET요청이 된다.
fetch를 사용한 구조를 보면
fetch("https://swapi.dev/api/people/1")
.then((res)=>{
console.log("RESOLVED!");
})
.catch((e)=>{
console.log("ERROR!");
})
fetch는 프로미스를 반환하기 때문에
then과 catch를 사용할 수 있다.
fetch("https://swapi.dev/api/people/1")
.then((res)=>{
console.log("RESOLVED!");
res.json().then(data => console.log(data)) // 추가
})
.catch((e)=>{
console.log("ERROR!");
})
단점은 응답 객체의 본문이 자동으로 구문 분석이 안된다.
JSON을 반환하도록 요청 했다고 가정했을 때 json 메소드를 사용해야한다
json() 역시 프로미스를 반환하기 때문에 then 을 사용해야 한다.
리팩토링 해보면
fetch("https://swapi.dev/api/people/1")
.then((res)=>{
console.log("RESOLVED!");
return res.json(); // 수정
})
.then((data) => { // 추가
console.log(data)
})
.catch((e)=>{
console.log("ERROR!");
})
만약에 이후에 계속적인 요청이 필요하다면
fetch("https://swapi.dev/api/people/1")
.then((res)=>{
console.log("RESOLVED!");
return res.json();
})
.then((data) => {
console.log(data)
return fetch("https://swapi.dev/api/people/2"); // 추가
})
.then((res)=>{ // 추가
console.log("SECOND RESOLVED!");
return res.json();
})
.catch((e)=>{
console.log("ERROR!");
})
반환 해서 .then 으로 계속 이어가면 된다.
then은 계속 늘어나겠지면 선형적인 구조로 코드가 깔끔한 모습이다.
async await 을 이용하면 좀 더 리팩토링이 가능하다.
const load = async () => {
try {
const res = await fetch("https://swapi.dev/api/people/1/");
const data = await res.json();
const res2 = await fetch("https://swapi.dev/api/people/2/");
const data2 = await res2.json();
} catch (e) {
console.log("ERROR");
}
}
load();
async await 키워드로 비동기 처리를 했더니 좀더 깔끔해졌다.
비동기의 에러처리는 try ~ catch 문을 사용해야 하니
catch 로 에러까지 처리해 주었다.
res data를 id로 활용한다면 좀 더 깔끔한 코드가 나올 것이다.
이번 시간에는 fetch를 알아보았는데
아직은 JSON 구문 분석을 별도로 수행해야 하기 때문에 완전하진 않다.
다음 시간에 Axios를 한번 살펴봐야겠다.
'javascript' 카테고리의 다른 글
[JS] 객체 지향 프로그래밍(OOP) 팩토리 함수, 생성자 함수, class (0) | 2023.04.18 |
---|---|
[JS] axios와 headers (2) | 2023.04.17 |
[JS] JSON 파싱 (0) | 2023.04.11 |
[JS] async, await (0) | 2023.04.09 |
[JS] Promise (0) | 2023.04.05 |