최근에는 이런식으로 JavaScript 코드를 짜진 않는다고 한다 ^_^...
하지만 개념을 익히려고 코드를 작성하게 되었다.
이전 글과 이어지는 코드이다.
화면이 로드되면, 아래 코드가 실행되면서 _authCheck 에 의해 전송되는 응답 중 'code' 를 확인하여
200인 경우 회원 목록을 표현하고 아닐 시에는 로그인을 해달라고 요청한다.
function init(){
}
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
const serverRes = JSON.parse(xhttp.response);
console.log(serverRes.code)
if(serverRes.code == 200){
let userULine = document.createElement("ul");
for(let i=0; i<serverRes.result.length; i++){
let userId = serverRes.result[i].id;
let userName = serverRes.result[i].name;
let userInpoLine = document.createElement("li");
let userInpo = document.createTextNode("[ id ] " + userId +"[ Name ] :" + userName);
userInpoLine.appendChild(userInpo);
userULine.appendChild(userInpoLine);
}
document.getElementById("authorized_state").appendChild(userULine);
} else {
let noticeMessage = document.createTextNode("로그인 해주세요");
document.getElementById("authorized_state").appendChild(noticeMessage);
}
}
}
xhttp.open("GET", "http://localhost:3000/user", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.withCredentials = true;
xhttp.send();
여기서, 코드로 구분하는 것이 아니라 Session안의 값을 통해 구분하는게 더 이상적이라 생각이 들어
그 부분은 더 알아보도록 해야겠다.
객체를 반복문으로 꺼내주는데, JSON.parse형식으로 형변환해주어야 했다.
function logout(){
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
console.log(xhttp.response);
}
}
xhttp.open("POST", "http://localhost:3000/logout", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.withCredentials = true;
// 세션-쿠키 통신하기 위해 주는 속성값
xhttp.send();
}
그리고 로그아웃 버튼을 만들어 로그아웃을 구현하고자 하였다.
참고한 블로그
JS : [object Object] 형태 출력하기
✅ 자바스크립트 : (。・∀・) ノ゙ Object 정보 나와라, 얍!
velog.io
'Front-end > WEB (HTML CSS JS)' 카테고리의 다른 글
[Web] express 로그인 구현 front 작업부분 (0) | 2022.10.23 |
---|---|
[JavaScript] Promise (Custom적인 접근) (0) | 2022.10.14 |
[JavaScript] async & await 사용 (0) | 2022.10.14 |
[JavaScript] Promise(then, catch) (0) | 2022.10.14 |
[JavaScript] Call-Back 함수 (0) | 2022.10.11 |
댓글