최종 프로젝트 7 - js GET, POST 연동

r5z Yoon·2022년 12월 16일
0

중간 점검 때 결국 프론트에서 코멘트를 못 보여줬다. 그걸 오늘 작업했슨니다..

api.js

// 메뉴 코멘트 가져오기
async function getFoodComment(food_id) {
  const response = await fetch(`${backend_base_url}/foods/main/${food_id}/comment/`, {
    headers: {
      Authorization: "Bearer " + localStorage.getItem("access"),
    },
    method: "GET",
  });
  response_json = await response.json();
  return response_json;
}

// 메뉴 코멘트 등록
async function postFoodComment(food_id, newComment) {
  const response = await fetch(`${backend_base_url}/foods/main/${food_id}/comment/`, {
    headers: {
      "content-type": "application/json",
      Authorization: "Bearer " + localStorage.getItem("access"),
    },
    method: "POST",
    body: JSON.stringify({
      "comment": newComment,
    }),
  });

  if (response.status == 200) {
    alert("작성 완료!");
    window.location.reload();
  } else if (response.status == 400) {
    alert("댓글을 작성해 주세요!");
  } else {
    alert(response.status);
  }
}

detail.js

// 코멘트 조회
window.onload = async function loadDetail() {
  
  comment = await getFoodComment(food_id);
  console.log(response_json);

  const commentList = document.getElementById("comment-list")

  response_json.forEach(comment => {

    commentList.innerHTML += `
    <li class="media d-flex" style="margin-right: ">
    <img class="mr-3" src="../templates/mascot.jpeg" alt="프로필 이미지" width="50px" height="50px">
    <div class="media-body">
      <h5 class="mt-0 mb-1">${comment.user}</h5>
      ${comment.comment}
    </div>  
    `

  });
}

// 댓글 작성
async function submitComment() {
  const newComment = document.getElementById("new-comment").value;
  const response = await postFoodComment(food_id, newComment)
}

문법이나 작동 방식을 이해 못한 채로 다른 페이지에서 구현한 것과 비슷하게 쓰면 되겠거니.. 하고 마구 작성만 하다 보니 시간만 엄청 쓰고 절대로! 프론트에 나타나지 않던 것들이 이제야...


415 Unsupported Media Type 에러

진짜 데이터타입도 제대로 넘겨주고 있었기에 도대체가 에러를 잡을 수가 없었는데요, 헤더에 실을 "content-type": application/json 을 applications 로 쓰고 있었다는 사실~~~
며칠 전엔 Bearer 뒤에 띄어쓰기가 없었고 그랬다지 😇🔫


콘솔이랑 서버에 찍히는 에러 메시지를 잘 읽고 노려보자 그러면 답이 있나니...
profile
_____ is a process </br> https://github.com/R5Z

0개의 댓글