본문 바로가기
Develop/JPA

마이페이지 회원정보 수정로직 (13)

by ys2ys2 2024. 11. 25.

마이페이지에서 회원정보 수정하는 로직을 짜고 있다.

 

 

 

회원 정보 수정을 누르면 새 창이 열리고 세션에 저장되어 있는 회원 이름, 이메일 주소를 보여주게 된다.

 

 

 

그 후 개인 정보 관리 버튼을 누르면 비밀번호 재확인을 해서 본인인증 프로세스를 거치게 된다.

 

 

비밀번호가 확인되면 서버에서 클라이언트로 다시 체크 성공 값을 보내고

성공 값이 들어오면 회원정보 수정할 수 있는 칸이 나와서 최종적으로 회원정보를 수정할 수 있게 된다.

 

이건 내일 추가할 예정!

 

백엔드 재밌는데 지금 당장 해야할게 너무 많다. 포폴 정리도 해야하고 자소서도 써야하고 바쁘다 바빠!

 

(몸살 이슈로 약먹고 꾸벅꾸벅 졸다가 갑자기 일어나서 열심히 썼으니까 오블완씨! 선물 주세요!)

 

 


 

 

오류 해결 과정

1. 클라이언트에서 데이터를 json으로 전달하게 했는데 서버에서 json 처리를 못하는 현상 발생

 

오류내용

Sending password to: /check_password
updatelogic:93 Password payload: {"password":"1234"}
updatelogic:105 Response status: 200
updatelogic:106 Response content type: application/xml;charset=UTF-8
updatelogic:123 Error: SyntaxError: Unexpected token '<', "<Map><mess"... is not valid JSON

 

클라이언트에서 JSON으로 전송되게 처리한 부분

document.getElementById('passwordForm').addEventListener('submit', (event) => {
event.preventDefault();

const password = document.getElementById('password').value;
console.log("Sending password to:", `${contextPath}/check_password`);
console.log("Password payload:", JSON.stringify({ password }));

fetch(contextPath + "/check_password", {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ password }), // JSON으로 전송
})
    .then((response) => {
        console.log("Response status:", response.status);
        console.log("Response content type:", response.headers.get("Content-Type"));

        if (!response.ok) {
            throw new Error('서버 오류가 발생했습니다.');
        }

        return response.json(); // JSON 파싱
    })
    .then((data) => {
        console.log("Response data:", data);
        if (data.status === 'success') {
            alert(data.message);
        } else {
            alert(data.message);
        }
    })
    .catch((error) => {
        console.error('Error:', error);
        alert('서버와 통신 중 문제가 발생했습니다.');
    });
});

 

 

서버 컨트롤러에서 JSON 처리한 부분

@PostMapping
@ResponseBody
public Map<String, Object> checkPassword(@RequestBody Map<String, String> requestBody, HttpSession session) {
    Map<String, Object> response = new HashMap<>();

    try {
        String password = requestBody.get("password");
        UserEntity user = (UserEntity) session.getAttribute("user");

        if (user == null) {
            System.out.println("Session user is null");
            response.put("status", "error");
            response.put("message", "로그인 정보가 없습니다. 다시 로그인해주세요.");
            return response;
        }

        System.out.println("User password in session: " + user.getCarPw());

        if (user.getCarPw().equals(password)) {
            session.setAttribute("isPasswordVerified", true);
            response.put("status", "success");
            response.put("message", "비밀번호가 맞습니다!");
        } else {
            response.put("status", "error");
            response.put("message", "비밀번호가 틀렸습니다!");
        }
    } catch (Exception e) {
        System.err.println("Error in checkPassword: " + e.getMessage());
        response.put("status", "error");
        response.put("message", "서버에서 오류가 발생했습니다.");
    }

    return response;
}

 

 

해결 방법

스프링부트에서 JSON 응답을 보장받으려면 컨트롤러 응답의 content-type을 application/json으로 명시해줘야 한다.

 

수정한 부분

@PostMapping(value = "/check_password", produces = "application/json")

 

결과

 

이제 이 반환값으로 다음 로직(회원정보 수정) 처리하기!

'Develop > JPA' 카테고리의 다른 글

마이페이지 회원정보 수정 로직 (14)  (2) 2024.11.26
마이페이지에 백엔드 작업하기 (11)  (2) 2024.11.21
반응형 CSS 추가하기 (10)  (1) 2024.11.20
반응형 CSS 추가하기 (9)  (0) 2024.11.19
카카오 길찾기 API (8)  (6) 2024.11.18