Research/HTML
HTML_JS fetchAPI로 서버 데이터 호출 후 HTML에 출력하기
RIEM
2023. 4. 14. 02:40
nest.js 서버 구축 중 프론트를 표현하고 싶었는데, HTML에서 API로 데이터를 호출하는 방법이 필요했다. 이를 위해 JS의 fetchAPI를 사용하여 해결하면 된다.
<html>
<head>
<meta charset='utf-8' />
<title>App</title>
<link href='styles.css' rel='stylesheet' />
<style>
h1 { color: salmon;}
</style>
</head>
<body>
<h1>Title</h1>
<div class='test'>hello</div>{{message}}
<form action='localhost:3000/news/log' method='get'>
<button type='submit'>Send GET Request</button>
</form>
<ul></ul>
<script src='js/scripts.js'></script>
<script>
fetch('http://localhost:3000/news/fake') .then(res => res.json())
.then(data => { data.forEach(user => { const markup =
`<li>${user.name}</li>`
document.querySelector('ul').insertAdjacentHTML('beforeend', markup) })
console.log(data); }) .catch(error => console.log(error))
</script>
</body>
</html>
Reference
https://www.youtube.com/watch?v=zUcc4vW-jsI