HTTP Crash Course & Exploration
https://www.youtube.com/watch?v=iYM2zFP3Zn0
https://www.youtube.com/watch?v=4K33w-0-p2c
원래는 이렇게 하면 된다고 한다.
#1 (this video) - Using XMLHttpRequest:
const getData = () => {
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://reqres.in/api/users");
xhr.responseType = "json";
xhr.onload = () => {
const data = xhr.response;
console.log(data);
};
xhr.send();
};
이렇게 할 수도 있다.
const sendHttpsRequest = (method, url, data) => {
const promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = "json";
if (data) {
xhr.setRequestHeader("Content-Tpye", "application/json");
}
xhr.onload = () => {
resolve(xhr.response);
};
xhr.onerror = () => {
reject("Something went wrong!");
};
xhr.send(JSON.stringify(data));
});
return promise;
};
const getData = () => {
sendHttpsRequest("GET", "https://reqres.in/api/users").then(
(responseData) => {
console.log(responseData);
}
);
};
const sendData = () => {
sendHttpsRequest("POST", "https://reqres.in/api/register", {
email: "eve.holt@reqres.in",
password: "pistol",
})
.then((responseData) => {
console.log(responseData);
})
.catch((err) => {
console.log(err);
});
};
#2 - Using the fetch() API:
https://academind.com/tutorials/xhr-fetch-axios-the-fetch-api/
const getData = () => {
fetch("https://reqres.in/api/users")
.then((response) => {
return response.json();
})
.then((responseData) => {
console.log(responseData);
});
};
이렇게 해서 getData를 첫번째것을 json으로 바꿔주고 console.log를 찍으면 되게 된다.
const sendHttpRequest = (method, url, data) => {
return fetch(url).then((response) => {
return response.json();
});
};
const getData = () => {
sendHttpRequest("GET", "https://reqres.in/api/users").then((responseData) => {
console.log(responseData);
});
};