api를 호출하기 위한 함수
호출이 오면 응답하는 함수
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<ul id="category-list">
</ul>
</div>
<script src="src/index.js">
</script>
</body>
</html>
div id가 app인 박스 안에 ul 아이디인 category-list를 생성해주어서 ul 안에 li로 카테고리 이름을 출력하려고 한다.
const category = fetch('<https://api.kurly.com/v2/categories>')
.then(res => {
return res.json();
})
.then(res => {
console.log(res);
const list = document.getElementById("category-list");
res.data.categories.forEach(el => {
const li = document.createElement("li");
li.innerHTML = el.name
list.appendChild(li)
})
})
우선 마켓컬리의 카테고리를 fetch 함수로 통해 api 호출해주었다.
then 함수로 응답을 받아 res를 인자로 받아서 res.json를 통해 형태가 가져왔다.
다시 then 함수로 json을 가져와 그 안의 categories의 객체를 forEach로 돌려서 li로 리스트로 출력해주었다.
👆위의 리스트를 보면 ul와 li의 형태로 가져온 내용이 잘 출력됐다는 걸 알 수 있다.
👆인자인 res를 출력하면 이런 식으로 객체를 받아서 콘솔창에 찍어 확인할 수 있다.