JavaScript fetch()

김혜림·2023년 5월 17일
0

javascript

목록 보기
2/4

API의 응답을 받아오기 위한 방법으로,
브라우저에서 자바스크립트의 fetch(url) 함수를 지원합니다.

fetch(url, option) : url 인자를 받아서 Promise 객체를 반환합니다.

fetch("https://jsonplaceholder.typicode.com/posts/1").then((response) =>
  console.log(response)
);

위와 같이 작성하면 "https://jsonplaceholder.typicode.com/posts/1" 링크의 응답을 받는 데에 성공하면 .then에서 전달한 resolve 콜백 함수를 실행할 겁니다.

대부분의 Rest API들은 JSON 형태의 데이터를 응답으로 전달합니다.

위의 예제의 https://jsonplaceholder.typicode.com/posts/1 을 브라우저에서 들어가보면

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

이런 결과를 볼 수가 있는데요, 저 형식이 JSON 형식입니다.

fetch(url)로 받은 JSON 결과를 .json() 메소드를 이용해서
자바스크립트 객체로 변환해줍니다.

위와 같은 방법으로 API응답을 가져와서 자바스크립트 파일에서 조작해서 웹페이지나 앱의 화면에 원하는 형태로 출력하는 것이죠.

반대로, 서버로 데이터를 보내려고 할 때는 자바스크립트 객체를 JSON.stringify()를 사용해서 JSON 문자열로 변환해주어야 합니다.

profile
공부하는 혜림이😀

0개의 댓글