나만의 작은 도서관

[TIL] 240718 캠프 95일차: Insomnia없이 JS에서 http Method를 요청 본문

Today I Learn

[TIL] 240718 캠프 95일차: Insomnia없이 JS에서 http Method를 요청

pledge24 2024. 7. 19. 09:38

오늘 배운 내용                                     

Insomnia없이 JS에서 http Method를 요청

이전까지는 Insomnia를 통해 GET, POST등 http Method들을 서버에 요청했다. 하지만 이번엔 버튼을 누르면 http Method(특히, GET)를 요청하도록 만들고 싶었기 때문에 자바스크립트에서 작성해야만 했다. 

 

사용방법은 아래와 같다.

 

클라이언트 코드

 

이 코드는 사이트 DB에 있는 유저 최고점수 리스트를 뽑아오는 API에 데이터를 요청하는 코드이다. 여기서 알아두어야 할 점은 GET 메소드인 경우 서버에 넘겨주어야할 데이터는 query방식으로 넘겨주어야 한다는 것이다. body에 데이터를 넣어줄 경우, GET은 body를 사용할 수 없다는 오류가 발생하게 된다.

 // 올바른 예
 const params = new URLSearchParams({ userId });
 const res = await fetch(`http://127.0.0.1:3000/rank/userHighscore?${params.toString()}`, {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'include',
 });
 
 // 오류나는 예
  const res = await fetch(`http://127.0.0.1:3000/rank/userHighscore`, {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'include',
    body: {userId}
 });

 

서버 코드

 

서버 코드에서는 기존에 알고 있던 대로 사용하면된다. 쿼리 스트링으로 데이터를 전송해주었음으로 req.query.userId로 데이터를 가져와 반환해준다.

// 해당 유저 점수 랭킹 조회 API.
router.get('/userHighscore', async (req, res) => {
  const userId = req.query.userId;
  console.log('userId', userId);
  try {
    const userHighscoreList = await getUserHighscoreList(userId);

    console.log('userHighscoreList', userHighscoreList);

    return res.status(200).json({ message: 'success get userHighscoreList', userHighscoreList });
  } catch (err) {
    return res.status(500).json({ err: `server Error ${err}` });
  }
});

 

다시 클라이언트 코드

 

서버로부터 돌려받은 내용(res)은 ok속성을 통해 데이터가 존재하는 지 알 수 있다. 아래 코드에서는 기대하는 데이터가 존재하지 않은 경우 alert()을 띄어 해당 사실을 클라이언트에게 알려주고 있다.

기대하는 데이터가 존재한다면, .json을 통해 JSON으로 변경해주고 넣었던 데이터를 가져오면된다.

if (!res.ok) {
    alert('유저 데이터 조회 실패');
    return;
}

const data = await res.json();
const userHighscoreList = data.userHighscoreList;
// console.log("userHighscoreList cli", userHighscoreList); 

// 랭킹 데이터를 테이블에 추가
userHighscoreList.forEach((data, index) => {
const row = document.createElement("tr");
row.innerHTML = `
          <td>${index + 1}</td>
          <td>${data.highscore}</td>
      `;
$tableBody.appendChild(row);
});

 

html파일에서 <script>태그에 들어있는 JS파일에서 다른 JS파일을 import를 할 수 있다.

되게 당연한 이야기이다. 시도때도없이 JS파일끼리 import를 사용했음에도 html파일에서는 왠지 안될 것 같은 느낌에 어렵게 생각했는데 html파일에 <script>태그로 묶인 JS코드이든, 그냥 자바스크립트 파일(ex. something.js)이든 import되는 방식은 동일하다. 그래서 AWS에 배포를 하게되면서 fetch()함수에 들어가는 서버 주소를 변경해야할 때 아래와 같이 상수를 저장하는 자바스크립트 파일에서 HOST, PORT데이터를 가져와 사용할 수 있다.

<script type="module">
    import { HOST, PORT } from './src/Constants.js';

    .
    .
    .
    const res = await fetch(`http://${HOST}:${PORT}/rank/userHighscore?${params.toString()}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
      });

     .
     .
     .
</script>

오늘 한 일                                       

더보기
  • 타워 디펜스 온라인 팀 프로젝트 최종 제출 및 피드백으로 인한 추가 구현