ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 23-06-26 ~ 23-07-02 WIL
    WIL 2023. 7. 4. 10:29

    이번주에 한 것

    neewsfeed 팀 프로젝트

    https://github.com/joungheunKim/nbc_game_review_web

     전반적인 html 연결을 맡아 진행 하였다.

     

    어려웠던 것

    처음 생각하기에 프론트 연결은 그렇게 어렵지 않을 것 이라 생각했기에,

    다른 팀원들의 백업과, route작성이 완료 되면 한 번에 연결을 할려고 했으나,

    막상 해보니 프론트를 짜는 것도 힘들었고, 연결이 내마음대로 되지 않아 힘들었다.

    post, put, delete method의 연결 작업은 순조롭게 되었는데

    get 연결 작업이 쉽지 않았다.

    연결 자체는 성공하였지만, 정보를 가져오지 못하는 것이 보여 왜 이런가에 대해 고민이 많았다.

    어떻게 해결 했나?

    고민과 구글링을 하던 중 알게 되었다.

    get 요청을 보낸다면, 말그대로 데이터를 받긴하지만, 프론트에선 그 데이터를 받아줄 변수가 없었기에 

    연결을 하여도 데이터를 가져오지 못 한 것이다.

    router.get("/posts", async (req, res) => {
        try {
            const posts = await Posts.findAll({
                attributes: ['post_id', 'user_id', 'title', 'game_title', 'genre', 'content', 'createdAt'],
                order: [['createdAt', 'DESC']]
            });

            if (posts.length !== 0) {
                const results = posts.map(post => {
           
                  return {
                    postId: post.post_id,
                    title: post.title,
                    content: post.content,
                    genre: post.genre,
                  };
                });
                res.status(200).json({ results })
              }
              else {
                res.json({ message: "피드가 존재하지 않습니다." });
              }

            //return res.status(200).json({ data: posts });
        } catch (error) {
            console.error(error);
            return res.status(400).json({ errorMessage: "게시글 조회에 실패하였습니다." });
        }
    });

    route에서 result 라는 변수에 내가 원하는 정보를 담아 보내주게 하였고

    그것을 프론트 연결 js에서 가져와 보여준다.

    이것을 하지 못하여 많은 어려움이 있었던 것 같다.

    //피드 불러오기
    window.addEventListener("DOMContentLoaded", async function(){
        fetch("/api/posts",{})
        .then((response) => response.json())
        .then((data) => {
            let rows = data["results"];
            const cardList  = document.getElementById("cardList")
            rows.forEach(post => {
                const title = post["title"]
                const genre = post["genre"]
                const content = post["content"]
                const postId = post["postId"]
                const temp_html = `<div class="card">
                <h3 class="tit" id="title">${title}</h3>
                <h5 id="genre">${genre}</h5>
                <p class="desc">${content}</p>
                <button type="button" class="more" class="ir" id="${postId}" onclick=window.location.href='/postdetail.html?id=${postId}'>더보기</button>
              </div>`;
               cardList.insertAdjacentHTML("beforeend", temp_html)

            });
        });

    })

    이렇게 받아온 정보를 뿌려주어야 비로서 get이 완료 된 것이다.

     

    느낀 점

    프론트연결을 하는 것도 결국 백단에서 하여야하는 것인데 연결을 용이하게 할려고 한다면,

    처음 코드를 짤때, 무엇이 필요하고 그것을 어떻게 보내줄 것인가? 이런 고민도 필요하다고 느꼈다.

    'WIL' 카테고리의 다른 글

    23-07-10 ~ 23-07-16 WIL  (0) 2023.07.16
    23-07-03~ 23-07-09 WIL 좋아요 기능 만들어보기  (0) 2023.07.10
    23-06-19 ~ 23-06-25 WIL  (0) 2023.06.26
    23-06-12~23-06-18  (0) 2023.06.18
    23-06-05 ~ 23-06-11 WIL  (0) 2023.06.11
Designed by Tistory.