/ JS

(자바스크립트) Ajax에서 페이지 이동 후 서버에 요청보내기


구현하고 싶은 목표

Ajax를 통해 서버와 연동하는 과정에서 로그인 후 로그인 한 유저의 데이터만을 메인 화면에 뿌려주고 싶었다.

  • 로그인 위해 아이디와 패스워드를 ajax로 body안에 담아 post요청
  • 서버에서는 DB에서 유저 정보 확인 후 jwt 토큰을 생성하여 클라이언트에 전송
  • 클라이언트는 받은 jwt를 localstorage에 저장
  • window.location.replace("http://127.0.0.1:5501/"); 로 메인 화면 이동
  • 이때 메인화면에 로그인 한 유저의 글만 보이게 하기 위해서는 ?

해결방법은 생각보다 간단했다. 나는 .js파일을 따로 분리해주었다. login에 관련된 js파일을 따로 만들어서 login.html페이지에 해당 js파일만을 넣어주었다.
이렇게 되면 메인화면으로 렌더링 되어도 실행되는 js파일이 main.js로 login과 분리되어 있기 때문에 서버에 메인 화면에 대한 정보를 요청할 수 있다


const Login = () => {
   $username = document.querySelector('.username').value;
   $password = document.querySelector('.password').value;
   param = {
     'username': $username,
     'password': $password
   }
     fetch("http://127.0.0.1:8000/user/login/", {
       method: 'POST',
       body: JSON.stringify(param)
     }).then(function (response) {
       return response.json()
     }).then(function (data) {
       localStorage.setItem('access_token',data['token'])
       // getTodos();
       window.location.replace("http://127.0.0.1:5501/"); # 메인 화면으로 이동된다
       return data
     }).catch((error) => {
       console.log('error', error);
     })
   }


메인화면 main.js

메인화면으로 이동시 document.addEventListener("DOMContentLoaded", getTodos); 가 먼저 실행되기 때문에 getTodos의 함수를 바로 실행시킬 수 있다. getTodos안에는 서버에 token에 해당하는 유저의 데이터를 요청하는 ajax가 있다.


}

const getTodos = () => {
  if (localStorage.getItem('access_token') ==  null){
    window.location.replace("http://127.0.0.1:5501/login.html");
  }
  Authorization = localStorage.getItem('access_token')
  fetch("http://127.0.0.1:8000/", {
    method: 'GET',
    headers: {
      
      "authorization":Authorization,
    },
  }).then(function (response) {
    return response.json()
  }).then(function (data) {
    console.log(data['user'][0]['userid'])
    console.log(data)
    document.querySelector('.main-user-infor').innerText = `환영해요 ! ${data['user'][0]['userid']}님`
    for (let i = 0; i < data['articles'].length; i++) {
      let create_date = new Date(parseInt(data['articles'][i]['created_at']) * 1000);
      create_date = create_date.getFullYear() + "/" + (create_date.getMonth() + 1) + "/" + create_date.getDate()
      console.log(data['articles'][i]['id'])
      $mainItems.innerHTML +=
        `<li class="li-item li-item${data['articles'][i]['id']}">
      <img src="${data['articles'][i]['image']}" alt="item이미지" class="img">
      <span class="far fa-times-circle item-close" onclick = deleteItem('${data['articles'][i]['id']}')></span>
      <span class="li-date">${create_date}</span>
      <span class="li-title">${data['articles'][i]['title']}</span>
    </li>`
    }
  }).catch((error) => {
    console.log('error', error);
  })
}
document.addEventListener("DOMContentLoaded", getTodos); // 화면 로딩되면 가장 먼저 getTodos 함수 실행시키기


내가 해결한 방법은 이렇게 js파일을 따로 분리하여 js파일이 실행될때 가장 먼저 실행되어야 하는 함수를 실행시키는 방법이였다. 더 좋은 방법이 있겠지만 현재 나는 이렇게 해결했다