자바스크립트/비동기

fetch를 이용해 서버의 데이터를 가져오는 방법

Socratone 2020. 4. 9. 22:11

const server = 'https://koreanjson.com/posts/1';

 

fetch(server)

    .then(response => response.json())

    .then(json => console.log(json))

    .catch(error => console.log(error));

 

// 각 메소드는 Promise 객체를 리턴한다.

// 1줄에서 가져온 것을

// 2줄에서 받아 json 형태로 바꾸고

// 3줄에서 json을 콘솔에 보여준다.

// error가 발생하면 콘솔에 error를 표시한다.

 

참고 : https://koreanjson.com/