회원가입 페이지(SignUp) 을 구현해보자

SignUp/index.tsx

import axios from "axios";
import React, { useState } from "react";
import * as _ from "./style";

const SignUp = () => {
  const [userEmail, setUserEmail] = useState<string>("");
  const [userPassword, setUserPassword] = useState<string>("");
  const [userPasswordCheck, setUserPasswordCheck] = useState<string>("");
  const [userNickname, setUserNickname] = useState<string>("");
  const [userPhoneNumber, setUserPhoneNumber] = useState<string>("");
  const [userAddress, setUserAddress] = useState<string>("");
  const [userAddressDetail, setUserAddressDetail] = useState<string>("");

  const handleSignUp = () => {
    const data = {
      userEmail,
      userPassword,
      userPasswordCheck,
      userNickname,
      userPhoneNumber,
      userAddress,
      userAddressDetail,
    };

    axios
      .post("http://localhost:4000/api/auth/signUp", data)
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(`${err} :: 회원가입 실패`);
      });
  };

  return (
    <_.SignUpContainer>
      <_.SignUpForm>
        <_.SignUpInput
          type="text"
          name="email"
          placeholder="이메일을 입력해주세요"
          onChange={(e) => {
            setUserEmail(e.target.value);
          }}
        />
        <_.SignUpInput
          type="password"
          name="password"
          placeholder="비밀번호를 입력해주세요"
          onChange={(e) => {
            setUserPassword(e.target.value);
          }}
        />
        <_.SignUpInput
          type="password"
          name="passwordCheck"
          placeholder="비밀번호를 확인해주세요"
          onChange={(e) => {
            setUserPasswordCheck(e.target.value);
          }}
        />
        <_.SignUpInput
          type="text"
          name="nickname"
          placeholder="닉네임을 입력해주세요"
          onChange={(e) => {
            setUserNickname(e.target.value);
          }}
        />
        <_.SignUpInput
          type="text"
          name="phoneNumber"
          placeholder="휴대폰번호를 입력해주세요"
          onChange={(e) => {
            setUserPhoneNumber(e.target.value);
          }}
        />
        <_.SignUpInput
          type="text"
          name="address"
          placeholder="주소를 입력해주세요"
          onChange={(e) => {
            setUserAddress(e.target.value);
          }}
        />
        <_.SignUpInput
          type="text"
          name="addressDetail"
          placeholder="상세주소를 입력해주세요"
          onChange={(e) => {
            setUserAddress(e.target.value);
          }}
        />
        <_.SignUpButton onClick={() => handleSignUp()}>회원가입</_.SignUpButton>
      </_.SignUpForm>
    </_.SignUpContainer>
  );
};

export default SignUp;

SignUp/style.ts

import styled from "styled-components";

export const SignUpContainer = styled.div`
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
`;

export const SignUpForm = styled.form`
  width: 500px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-top: 150px;
`;

export const SignUpInput = styled.input`
  width: 80%;
  height: 40px;
  border: 0.5px solid gray;
  margin-top: 20px;
`;

export const SignUpButton = styled.button`
  width: 80px;
  height: 40px;
  border: 0.5px solid gray;
  margin-bottom: 20px;
  background-color: darkblue;
  color: white;
  margin-top: 40px;
`;

styled-components 를 이용해 CSS를 구현하였다.

package com.hyeonjoonpark.board_crud.Controller;

import com.hyeonjoonpark.board_crud.Dto.ResponseDto;
import com.hyeonjoonpark.board_crud.Dto.SignupDto;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @PostMapping("/signUp")
    public ResponseDto<?> signUp(@RequestBody SignupDto requestBody) {
        System.out.println(requestBody.toString());
        return null;
    }
}

Request 받은 값을 출력해보면 백엔드 서버로 데이터가 잘 들어오는 것을 알 수 있다.


Service라는 패키지를 하나 만들고 AuthService 클래스를 만들어주자

Service는 클라이언트와 서버의 접점이고 Repository는 DB와 서버의 접점이다

인터페이스로 만들어서 상속받는 것이 좋은 방법이지만 지금은 Class로 만든 다음 나중에 수정해보겠다

package com.hyeonjoonpark.board_crud.Service;

import com.hyeonjoonpark.board_crud.Dto.ResponseDto;
import com.hyeonjoonpark.board_crud.Dto.SignupDto;
import org.springframework.stereotype.Service;

@Service
public class AuthService {
    public ResponseDto<?> signUp(SignupDto dto) {
        String userPassword = dto.getUserPassword();
        String userPasswordCheck = dto.getUserPasswordCheck();
        
        if(userPassword.equals(userPasswordCheck)) {
            return ResponseDto.setFailed("Password is not Existed");
        } // userPassword와 userPasswordCheck가 일치하지 않으면
    }
}

UserEntity에 생성자를 만들어보자

package com.hyeonjoonpark.board_crud.Entity;

import com.hyeonjoonpark.board_crud.Dto.SignupDto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity(name="User")
@Table(name="User")
public class UserEntity {
    @Id
    private String userEmail;
    private String userPassword;
    private String userNickname;
    private String userPhoneNumber;
    private String userAddress;
    private String userProfile;

    public UserEntity(SignupDto dto) {
        this.userEmail = dto.getUserEmail();
        this.userPassword = dto.getUserPassword();
        this.userNickname = dto.getUserNickname();
        this.userPhoneNumber = dto.getUserPhoneNumber();
        this.userAddress = dto.getUserAddress() + " " + dto.getUserAddressDetail();
    }
}

다음과 같이 생성자를 작성하면

package com.hyeonjoonpark.board_crud.Service;

import com.hyeonjoonpark.board_crud.Dto.ResponseDto;
import com.hyeonjoonpark.board_crud.Dto.SignupDto;
import com.hyeonjoonpark.board_crud.Entity.UserEntity;
import org.apache.catalina.User;
import org.springframework.stereotype.Service;

@Service
public class AuthService {
    public ResponseDto<?> signUp(SignupDto dto) {
        String userPassword = dto.getUserPassword();
        String userPasswordCheck = dto.getUserPasswordCheck();

        if(userPassword.equals(userPasswordCheck)) {
            return ResponseDto.setFailed("Password is not Existed");
        } // userPassword와 userPasswordCheck가 일치하지 않으면

        UserEntity userEntity = new UserEntity(dto); // UserEntity 생성
    }
}

Repository를 통해 DB에 넣으면 된다.

package com.hyeonjoonpark.board_crud.Service;

import com.hyeonjoonpark.board_crud.Dto.ResponseDto;
import com.hyeonjoonpark.board_crud.Dto.SignupDto;
import com.hyeonjoonpark.board_crud.Entity.UserEntity;
import com.hyeonjoonpark.board_crud.Repository.UserRepository;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthService {
    @Autowired UserRepository userRepository;
    public ResponseDto<?> signUp(SignupDto dto) {
        String userEmail = dto.getUserEmail();
        String userPassword = dto.getUserPassword();
        String userPasswordCheck = dto.getUserPasswordCheck();

        // email 중복 확인
        try {
            if(userRepository.existsById(userEmail)) { // userEmail이 존재하는지 확인 -> 존재 시 true 존재하지 않으면 false 반환
                return ResponseDto.setFailed("Existed Email!");
            }
        } catch (Exception e) {
            return ResponseDto.setFailed("Database Error");
        }

        if(!userPassword.equals(userPasswordCheck)) {
            return ResponseDto.setFailed("Password is Wrong!");
        } // userPassword와 userPasswordCheck가 일치하지 않으면

        UserEntity userEntity = new UserEntity(dto); // UserEntity 생성

        try {
            // UserRepository를 이용해서 DB에 Entity 저쟝
            userRepository.save(userEntity);
        } catch (Exception e) {
            ResponseDto.setFailed("Database Error");
        }
        
        return ResponseDto.setSuccess("SignUp Success!", null);
    }
}

userEmail을 받아와서 존재하는지 비교한다


AuthController에서 불러오자

package com.hyeonjoonpark.board_crud.Controller;

import com.hyeonjoonpark.board_crud.Dto.ResponseDto;
import com.hyeonjoonpark.board_crud.Dto.SignupDto;
import com.hyeonjoonpark.board_crud.Service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired AuthService authService;
    @PostMapping("/signUp")
    public ResponseDto<?> signUp(@RequestBody SignupDto requestBody) {
        ResponseDto<?> result = authService.signUp(requestBody);
        return result;
    }
}

다음편에서 계속

profile
Backend Developer

0개의 댓글