[Toy] restful api를 통한 FE, BE 협업 과정 정리(프론트 중심)

서연·2023년 8월 30일
0

toy-project-1

목록 보기
4/5
post-thumbnail

현재 기술 스택

  • FE : NodeJS - React
  • BE : Java - Spring
  • 환경이 완전히 분리된 상태에서 restful Api를 통해 데이터 주고 받음

BE가 제작한 api 목록

여기 참고하면 됩니다

React에서는 어떻게 데이터를 호출하고 받을 수 있는가?

환경 정리

  • apis : BE와 연결할 axios 함수들
  • assets : 이미지, 비디오, 폰트
  • components : 최소 단위의 컴포넌트들 저장 (ex. 버튼, 카드, 인풋)
  • constants : 상수들
  • interfaces : Type으로 사용할 인스턴스들 (Only typescripts)
  • stores : 스토어 함수들
  • utils : 각종 메서드들
  • views : 큰 페이지 혹은 레이아웃 단위의 컴포넌트

1. react는 컴포넌트 단위의 업데이트, 랜더링이 가능하게 함

  • 가능하게 돕는 것 : state, props를 통한 상속

2. axios로 회원가입, 로그인, 로그아웃 구현하기

2-1. api 관리

// path : api/index.ts

export const SignInApi = async (data: any) => {
    
    const response = await axios.post("http//localhost:4000/api/auth/signIn", data).catch((error) => return null);
    if (!response) return null;
    
    const result = response.data;
    return result;
}


export const SignUpApi = async (data: any) => {
    
    const response = await axios.post("http//localhost:4000/api/auth/signUp", data).catch((error) => return null);
    if (!response) return null;
    
    const result = response.data;
    return result;
}

2-2. 회원가입

// path : views/Athentification/SignUp/index.tsx

import React from 'react'

export default function SignUp() {
    const [userEmail, setUserEmail] = useState<string>('');
    const [userPassword, setPassword] = useState<string>('');
    const [userPasswordCheck, setUserPasswordCheck] = useState<string>('');
    const [userNickname, setUserNickname] = useState<string>('');
    const [userPhoneNumber, setUserPhoneNumber] = useState<string>('');
    const [userGender, setUserGender] = useState<string>('');

    const SignUpHandler = async () => {
        const data = {
            userEmail,
            userPassword,
            ...
        };

        const signUpResponse = await SignUpApi(data);
        if (!signUpResponse) {
            alert('회원가입에 실패했습니다');
            return;
        }
        alert('회원가입에 성공했습니다');
      
    }
  return (
    { user != null && (<>{user.userNickname}</>)}
    <div>
        <TextField fullWidth label="이메일 주소" type="email" variant="standart" onClick={(e) => setUserEmail(e.target.value)} />
    </div>
  )
}

2-3. 로그인

// path : views/Athentification/SignIn/index.tsx
import React, { useState } from 'react';
import axios from "axios";
import { useCookies } from "react=cookie";

export default function SignIn() {
    const [email, setEamil] = useState<string>('');
    const [password, setPassword] = useState<String>('');

    const [cookies, setCookies] = useCookies();

    const {setUser} = useUserStore(); //store에 저장함으로써 외부에서 관리됨

    const signInHandeler = async () => {
        if (email.length === 0 || password.length === 0){
            alert('이메일과 비밀번호를 입력하세요');
            return;
        } 
        
        const data = {
            userEmail,
            userPassword
        }

        const signInResponse = await signInApi(data);

        if (!signInResponse) {alert('로그인에 실패했습니다.');}
        if (!signInResponse.result) {
            alert('로그인에 실패했습니다.');
            return;
        }
        const { token, exprTime, user } = responseData.data;
        const expires = new Date();
        expires.setMillseconds(expires.getMilliseconds() + exprTime);

        setCookies('token', token, { expires });  // token이 쿠키에 등록됨 (토큰이 쿠키에 유지되는 동안은 로그인 중이라고 이해 가능)
        setUser(user);
    }
  return (
    <div>Untitled-1</div>
  )
}
  • 쿠키에 유저 정보를 등록하고 전역 user를 등록하는 과정

      const signInResponse = await signInApi(data);
      
      if (!signInResponse) {alert('로그인에 실패했습니다.');}
      if (!signInResponse.result) {
          alert('로그인에 실패했습니다.');
          return;
      }
      const { token, exprTime, user } = responseData.data;
      const expires = new Date();
      expires.setMillseconds(expires.getMilliseconds() + exprTime);
    
      setCookies('token', token, { expires });  // token이 쿠키에 등록됨 (토큰이 쿠키에 유지되는 동안은 로그인 중이라고 이해 가능)
      setUser(user);

2-4. header에 user token 정보 포함해서 axios.post 하는 법

const requestOption = {
    headers: {
        Authorization: `Bearer ${token}`
    }
};

const data = {
    // body 데이터 객체 형식으로 작성
    diaryDetail
    addDate
    // ...
};

await axios.post("http://localhost:4000/api/board/", data, requestOption)
    .then((response) => {
        setBoardResponse(response.data);
    })
    .catch((error) => {
        console.error(error);
    });

3. user token을 쿠키로 관리하고, 전역으로 토큰을 활용하는 법

// npm install react-cookie
// npm install zustand (보통 redux를 사용하는데 어려워서 이 강의에서 zustand 사용)


// stores/user.store.ts
import { create } from "zustand";

interface UserStore{
    user : any;
    setUser: (user: any) => void;
    removeUser: () => void;
}

const useStore = create<UserStore>((set) => ({
    user : null,
    setUser: (user: any) => {
        set((state) => ({...state, user}));
    },
    removeUser: () => {
        set((state) => ({...state, user: null}));
    },
}));

export default useStore

// stores/index.ts
import useUserStore from './user.store';

export {useUserStore};
profile
삽질 기록장/ 📍다른 삽질 기록장 https://sqlimblife.tistory.com/

0개의 댓글