✏️5주차 QUIZ

박시은·2023년 7월 8일
0

JavaScript

목록 보기
38/58
post-thumbnail

▶ Quiz. API 서버 통신 연습

이번 주 퀴즈는 API 서버 통신을 연습 해볼 겁니다.

JSONPlaceholder - Free Fake REST API

해당 사이트는 Fake API를 지원하는 서버로 프로미스를 공부할 때 참고가 되는 사이트입니다.

console.log(fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => console.log(json)));
//Promise { <pending> }
//{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }

fetch는 Promise를 반환하는 메서드입니다. console.log를 찍어보면 알 수 있죠


자 한번 api 서버를 호출하는 연습을 해봅시다!

위에서 소개한 웹 사이트에서 스크롤을 좀 아래로 내리다보면 사진과 같은 화면이 나옵니다.

빨간 박스안에 URL을 복사하면 api 서버 주소가 나오는데 6개 링크를 모두 한번씩 console.log로 찍어봅시다.

6개 코드와 결과를 캡처해서 올려주시면 됩니다.

예시)

async function api() {
	try {
		result = await fetch('https://jsonplaceholder.typicode.com/todos/').then(res => res.json());
	}
	catch (error){
		console.log(error);
	}
	console.log(result);
}

api();




▷ 풀이

이 풀이가 문제의 의도인진 잘 모르겠다. -> 맞다고 한다.

async function api() {
  try {
    const getPosts = await fetch(
      "https://jsonplaceholder.typicode.com/posts"
    ).then((res) => res.json());
    console.log(getPosts);

    const getComments = await fetch(
      "https://jsonplaceholder.typicode.com/comments"
    ).then((res) => res.json());
    console.log(getComments);

    const getAlbums = await fetch(
      "https://jsonplaceholder.typicode.com/albums"
    ).then((res) => res.json());
    console.log(getAlbums);

    const getPhotos = await fetch(
      "https://jsonplaceholder.typicode.com/photos"
    ).then((res) => res.json());
    console.log(getPhotos);

    const getTodos = await fetch(
      "https://jsonplaceholder.typicode.com/todos"
    ).then((res) => res.json());
    console.log(getTodos);

    const getUsers = await fetch(
      "https://jsonplaceholder.typicode.com/users"
    ).then((res) => res.json());
    console.log(getUsers);
  } catch (error) {
    console.log(error);
  }
}

api();

profile
블로그 이전했습니다!

0개의 댓글