관리 메뉴

Silver Library (Archived)

API for friendly version. 본문

Personal DB/Mainly for Front-end

API for friendly version.

Chesed Kim 2022. 10. 6. 22:08
반응형

크게 4가지의 방식이 있습니다.

1. XMLHttpRequest 2. fetch 3. Axios 4.jQuery

여기서, javascript 만을 이용해서 실현 해 보는 것에 중점을 두고 있습니다.

 

우선, XMLHttpRequest 의 경우:

let request = new XMLHttpRequest();
request.open("GET", "api uri address");
request.send();
request.onload = () => {
	console.log(request);
    if (request.status === 200) {
    	console.log(JSON.parse(request.response));
    } else {
    	consol.elog(`error ${request.status} ${request.statusText}`_
    }
}

이러면, string 으로서 response 를 받게 되며, 이를 JSON 으로 parsing 할 필요가 있습니다.

그런데 잠깐, XMLHttpRequest 는 fetch 로 대체되고 있는 상황입니다.

따라서, 이 글의 최종적인 목표는 fetch 의 사용법에 대해 알아보는 것 입니다. 

 

Fetch 의 경우,

promises 를 사용한다는 점. 그리고 구버전의 브라우저를 지원 하지 않는다는 점.

그리고, 2가지 방식이 있다는 점.

 

방법 1. 잘 알려진 방식

fetch('여기가 api uri')
	.then(response => {
    	return response.json();
    })
    .then(users => {
    	console.log(users);
    });

시작을 fetch 로 해서,

.then method를 사용. 그리고 이 것은 Promise API 와 관계가 있고, 비동기적인 API 와의 통신을 해내게 해 줍니다.

이 fetch 와 .then method 의 조합이란, callback function 을 사용하지 않고, 실현 해 낼 수 있는겁니다.

 

방법 2. Async 및 Await 를 사용하는 경우.

async function getUsers() {
	let response = await fetch('api uri address');
    let data = await response.json()
    return data;
}
getUsers().then(data => console.log(data));

위 방법 1과 차이점이 있다면, 시작부터 async function 으로 선언해서, await 를 사용 하여 reponse 와 communication 하는 구성입니다. async 로 function 을 정의 한 후, 비동기통신을 목적으로 await 를 사용하여 각 대상을 지정하여 구성합니다.

 

이 후, console.log 로 시행해보면 200 (OK) 가 표시됩니다.

 

.then method 란, 위에서 언급 한 대로 promise API 와 관계가 있고, 비동기적인 API 와의 통신 성사가 목적입니다.

그리고, 여기서 await 의 경우, 말 그대로 응답이 오기까지 기다립니다. 가 아니라, promise 를 기다리고자 사용되며, async block 내부에서만 제한적으로 사용됩니다.

 

예를 들어, await 라 존재하는 한, 설령 console.log 로 

const getData = async() => {
	var y = await "Hello World";
	console.log(y);
}

console.log(1);
getData();
console.log(2);

게 한들, 결과는 1, 2, Hello World 입니다.

 

그러나 fetch API 에도 단점이 있습니다. 알려진 것으로는 '에러 대응', 으로 보여집니다.

 

 

async function - JavaScript | MDN

async function 선언은 AsyncFunction객체를 반환하는 하나의 비동기 함수를 정의합니다. 비동기 함수는 이벤트 루프를 통해 비동기적으로 작동하는 함수로, 암시적으로 Promise를 사용하여 결과를 반환

developer.mozilla.org

 

 

Why we use then() method in JavaScript ? - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

 

All possible ways of making an API call in JavaScript

In JavaScript it was really important to know how to connect an application with API(Application Programming Interface) and required to…

levelup.gitconnected.com