프로젝트 백엔드 작업을 거의 마무리하고
프론트에서 DB에 저장 된 값을 불러오는 작업을 시작했다.
⬜ 백엔드에서 보낸 정보를 프론트로 받아오기
⬜ 그 중에 이미지만 추출해서 띄우기
⬜ 모든 게시글의 이미지를 순차적으로 띄우기
<!-- index.html -->
<body>
<h1>메인페이지</h1>
<button onclick="handleLoad()">정보 가져오기</button>
</body>
반응을 즉각적으로 확인하기 위해,
index.html에 정보를 가져오는 버튼을 만들었다.
// index.js
async function handleLoad(){
const response = await fetch("http://127.0.0.1:8000/", {
method: "GET"
})
const response_json = await response.json()
console.log(response_json)
}
그리고 index.js에는 버튼을 누르면 실행되는 handleLoad() 함수를 만들었다.
해당 함수가 실행되면,
fetch로 GET에 담긴 정보값을 가져오고,
그 정보값을 json데이터 형식으로 변환시켜준 뒤
console에 정보를 띄울 수 있게 했다.

메인 페이지다.

버튼을 누르면 console창으로 GET에 실어진 데이터 값이 무사히 들어오는 것을 볼 수 있다.
<!-- index.html -->
<div id="content-box"></div>
가져온 이미지를 넣어줄 div 박스를 만든다.
// index.js
const backend_adress = "http://127.0.0.1:8000/"
// 이미지를 넣어 줄 박스 지정
const contentBox = document.getElementById("content-box")
// 이미지 element 생성
const imageBox = document.createElement('img')
// 클래스 부여
imageBox.setAttribute("class", "img-box")
// 이미지 주소 설정
const imagePath = backend_adress + response_json[0]["image"]
// 링크 부여
imageBox.setAttribute("src", imagePath)
// 박스에 append
contentBox.append(imageBox)
이미지를 넣을 div박스를 id값으로 만들어 지정한 뒤,
json 값에서 이미지 주소를 찾아서 imagePath를 지정해준다.
그러고 나서 setAttribute로 src를 지정해서
div박스에 append해주면 끝.

이미지가 잘 붙는다!
서버를 구동해서 돌릴 경우 저 링크만 서버 주소로 바꿔주면 될듯.
여러 데이터를 순서대로 붙이려면 역시 for문이 좋지 않을까?
에서 힌트를 얻었다.
for (i = 0; i < response_json.length; i++){
const imageBox = document.createElement('img')
imageBox.setAttribute("class", "img-box")
const imagePath = backend_adress + response_json[i]["image"]
imageBox.setAttribute("src", imagePath)
contentBox.append(imageBox)
}
for문으로 전체를 감싸고,
response_json의 길이만큼 for문을 돌리며 사진을 붙인다!

한번에 이미지가 다 붙는다 !!
성공.
window.onload = async function() {
const response = await fetch(`${backend_adress}`, {
method: "GET"
})
}
해당 구조로 사용해주면 된다.
window.onload = () => {
console.log("로딩 완료!")
}
이건 async와 await를 사용하지 않을 경우