[React] fetch 함수를 이용한 회원가입 & 로그인 구현 실습

안정현·2021년 5월 9일
0

1. 전체적인 흐름
2. fetch 함수
3. Backend와 통신

1. 전체적인 흐름

1) 유저가 이메일을 입력. Email Input의 onChange 함수가 실행

2) onChange 함수에서 Email Input의 valuesetState를 통해 업데이트

3) 유저가 비밀번호를 입력. Password Input의 onChange 함수가 실행

4) onChange 함수 안에서 Password Input의 valuesetState를 통해 업데이트

5) Button을 클릭하면 onClick 함수가 실행

6) onClick 함수 안에서 fetch 함수를 통해 server에 요청(Request)을 보냄

7) server에서 인증 / 인가 과정을 거친 후의 결과를 응답(Response)으로 보내 줌

8) 응답의 결과에 따라 Main 페이지로 이동 하거나 에러 메세지를 띄움

2. fetch 함수

fetch("api주소", {
      method: "POST",
      body: JSON.stringify({
        email: this.state.id,
        password: this.state.pw,
      }),
    })
      .then((response) => response.json())
      .then((result) => console.log("결과: ", result));

1) 첫 번째 인자는 api 주소, 두 번째 인자는 http 통신에 관한 내용

2) 두 번째 인자

  • method는 GET, POST, PATCH 등 http method를 입력
  • JSON 형태로 데이터를 주고 받는데 이 데이터를 body에 넣음
    -> 통신을 할 때는 string 형태의 JSON으로 보내야 하기 때문에 JSON.stringify()라는 메서드를 활용해서 포맷을 기존의 Object에서 String으로 변환해줌
  • 통신은 다른 로직에 비해 오래 걸리기 때문에 비동기 처리돼서 then 메서드를 사용
.then((response) => response.json())

3) 첫 번째 then에서는 server에서 보내준 response를 Object 형태로 변환함

.then((result) => console.log("결과: ", result));

4) 두 번째 then에서는 object로 변환한 response를 console.log로 확인함.

  • 여기서 원하는 로직을 구현함
    -> 예를 들어,
    로그인 성공하면 main 페이지로 이동
    로그인 실패하면 alert 창에 "아이디나 비밀번호를 확인해주세요." 띄우기

3. Backend와 통신

  • Frontend와 Backend 모두 같은 네트워크 상에 있는 지 확인 필요
    * ex) wework Wi-Fi 에 접속되어 있는지 여부 체크

  • 화면에 id, pw 입력하는 input이 있음

  • 입력 후 "로그인" 버튼을 누르면 백앤드 로그인 api를 호출

fetch('http://10.00.0.00:8000/user/signin', {
  method: 'POST',
  body: JSON.stringify({
    email: this.state.idValue,
    password: this.state.pwValue,
  }),
})
  .then(response => response.json())
  .then(result => {
    if (result.MESSAGE === 'SUCESS') {
      localStorage.setItem('token', result.token);
      this.props.history.push('/Main');
    } else {
      alert('아이디나 비밀번호를 확인해주세요');
    }
  });
  • 로그인 성공의 경우
    - 백앤드: 정상 id/pw 경우에만 access token을 보냄
    - 프론트: alert로 로그인 완료 메시지를 보여주고 localStorage에 저장
fetch('http://10.00.0.00:8000/user/signin', {
  method: 'POST',
  body: JSON.stringify({
    email: this.state.idValue,
    password: this.state.pwValue,
  }),
})
  .then(response => response.json())
  .then(result => console.log('결과: ', result));
  • 로그인 실패의 경우
    - 백앤드: 어떤 실패인지 msg를 전달
    - 프론트: 받은 메시지를 alert로 보여줌

<출처> wecode(코딩 부트캠프) 세션

0개의 댓글