로그인 회원가입 & fetch 함수

Steve·2021년 10월 17일
0

goToMain = () => {
    fetch(`${BASE_URL}/users/signin`, { // 1번째 인자 : api주소
      method: 'POST',
      body: JSON.stringify({ //http통신을 할땐 JSON형식으로 통신 한다라고 규약돼있음. js객체를 JSON형식으로 바꿔달라라는 요청.
        email: this.state.email,
        password: this.state.password,
      }),
    })
      .then(res => res.json()) //JSON형식으로 통신했긷때문에 응답도 JSON으로 들어옴.그것을 js 객체형식으로 다시 바꿔주는 코드
      .then(res => { // js객체형식으로 바꾼것을 가지고 요리를 시작
        if (res.token) {
          localStorage.setItem('token', res.token);
          alert('로그인 되었습니다.');
          this.props.history.push('/');
        } else {
          alert('아이디와 비밀번호를 확인하세요');
        }
      });
  };

동기방식: 순차적으로 진행(한줄한줄 코드가 실행되야 다음줄로 진행됨)
비동기방식: 비순차적으로 진행( 한줄한줄 코드를 기다려주지 않음)

  • fetch함수는 비동기방식.
    왜?? >> HTTP 통신은 다른 로직에 비해 오래 걸리기 때문에 비동기로 처리함.
    통신이 완료될때까지 다음것들을 기다려야한다면 UX가 엉망진창 될것이다.
  • 통신을 할 때는 String 형태의 JSON으로 보내야 하기 때문에 JSON.stringify() 라는 메서드를 활용해서 포맷을 기존의 javascript object에서 JSON String으로 변환해줍니다.
    JS 에서 비동기를 처리하는 문법으로 Promise 객체가 있습니다.
    따라서 fetch 함수는 Promise 객체를 리턴 합니다.
    then() 메서드는 Promise 객체에 사용할 수 있는 메서드 입니다
    응답또한 JSON형식으로 오기때문에 js 객체형식으로 돌려줘야함<- then()1번째.

js객체형식된것을 이용하여 그다음 로직들 구현<- then() 2번째

GET vs POST

  1. GET
  • default method는 get입니다.

DB에서 데이터를 받아올때.
body: 가 필요없음.
DB에 데이터를 전달해줄 필요가 없기 때문.

  1. POST(로그인 / 회원가입할때)
    DB에 데이터를 넣거나, 수정,삭제 할때.

Fetch(GET)

설명: 유저 정보를 가져온다.
base url: https://api.google.com
endpoint: /user/3
method: get
응답형태:
{
"success": boolean,
"user": {
"name": string,
"batch": number
}
}

fetch('https://api.google.com/user/3')
.then(res => res.json())
.then(data => {
if(res.success){
console.log(`${res.user.name}님 환영합니다`);
}})

Fetch(POST)

*호출해야할 api가 get이나 post 뭐인지는 백엔드 개발자에게 물어봐야함.


```base url: https://api.google.com
endpoint: /user
method: post
요청 body:
    {
        "name": string,
        "batch": number
    }

응답 body:
    {
        "success": boolean
    }
fetch('https://api.google.com/user',{ 
method: post,
body : JSON.stringify({
        name: "steve",
        batch: 1
    })
})
.then(res => res.json())
.then(data => {
	if(res.success){
    	alert('저장 완료');
    }
})

2번째 인자로 method와 body보내준다.

  • 나중에 axios를 배워서 쓸때는 JSON.stringify를 해줄 필요가 없는 이점이 있다.
profile
Front-Dev

0개의 댓글