본문 바로가기
Development (국비 복습 )/JavaScript

api fetch() 써보기

by Puddingforever 2023. 3. 11.

오픈 서버로 부터 정보를 받아와서 데이터를 확인 할 수 있다.

구글링으로 free open api치면 많이 나온다.

fetch()를 사용하여 get방식으로 서버의 정보를 가져오며, async await 방법을 사용하여 데이터 정보를 받아온다.

const url = "http://worldtimeapi.org/api/timezone/Asia/Seoul";

async function getData(){
	const response = await fetch(url);
    const data = await response.json();
    console.log(data)
}

이때 , async - await 문법은 promise를 간소화한 문법이다.

저걸 원래 promise문법으로 쓴다면 , 

function getData(){
    return new Promise.resolve(url);
}

이런식으로 나올 것이다.

 

서버를 가져와 쓸 때, 저렇게 단순하게 가져오는 경우도 있지만 token을 요구하는 경우도 있다.

const url = "https://api.spotify.com/v1/artists/3Nrfpe0tUJi4K4DXYWgMUX?si=9uPODbLSS_uLC_56H0uBBg";
async function getData(){
    const request = new Request(url,{
        headers:{
            'Authorization':
            //토큰을 요구 
        }
    })
    const response = await fetch(request);
    const data = await response.json();
    console.log(data);
}
getData();

Get방식의 경우 단지 header만 있지만 Post방식은 데이터를 서버로 보내야하기 때문에 body도 있다.

 

'Development (국비 복습 ) > JavaScript' 카테고리의 다른 글

[JQuery] $.trim()의 용도  (0) 2023.03.11
[JQuery] document ready를 쓰는 이유  (0) 2023.03.10
입력창을 받는 alert인 prompt  (0) 2023.03.05
-prototype 정리  (0) 2023.03.02
자바스크립트 closure  (0) 2023.02.27

댓글