React 로 로그인 구현하기 ( 유효성 검사, CORS )

jaehan·2022년 8월 7일
0

React

목록 보기
10/33
post-thumbnail

유효성 검사

회원가입에서 이메일과 핸드폰번호의 유효성 검사할때는 정규식을 사용했다.

  const regEmail =
    /^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/;
  const regPhoneNumber = /^01(?:0|1|[6-9])-(?:\d{3}|\d{4})-\d{4}$/;

이메일은 문자 + @ + 문자 + . + 문자 의 형식이고

핸드폰 번호는 우리는 -를 사용하기 때문에 01?-3 or 4자리 숫자-4자리 숫자 형식으로 설정했다.

  const [emailValid, setEmailValid] = useState(true);
  const [emailErrorMessage, setEmailErrorMessage] = useState('');

  const checkEmailValid = (email: string) => {
    return regEmail.test(email);
  };
  const handleEmail = (e: ChangeEvent<HTMLInputElement>) => {
    setEmail(e.target.value);
    setEmailValid(checkEmailValid(e.target.value));
    setEmailErrorMessage(
      checkEmailValid(e.target.value) ? '' : 'Not a valid email address'
    );
  };

입력 받은 값을 checkEmailValid 함수의 인자로 주고 정규식.test로 검사해서 return 해주었다.

이벤트 핸들러로 입력값이 변할때 마다 유효성을 체크해서 vaild 값을 boolean 값으로 저장해주고 에러 메세지를 설정해 주었다.

<TextField
        variant="outlined"
        margin="normal"
        required
        fullWidth
        error={!emailValid}
        id="email"
        name="email"
        helperText={emailErrorMessage}
        label="Email Address"
        onChange={emailHandler}
      />

mui의 TextField의 error 값으로 유효성 체크한 boolean 값을 넣어주고 helpertext 값으로 정해준 에러 메세지를 넣어주었다.

CORS

배포 환경에서도 잘 되던 프론트가 쿠키 때문에 withCredentail 을 추가하니까 cors 오류가 생겨서 삽질을 엄청 했다.

간단하게 cors란

CORS는 Cross-Origin Resource Sharing의 약자로 직역하면 "교차 출처 리소스 공유" 이다.

좀 더 쉽게 말하면 동일한 출처가 아닌 다른 출처에서 데이터를 주고 받는 것을 허용하는 정책이다.

우리 배포환경에서 나왔던 오류 메세지는

Access to fetch at 'https://'배포 url' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

이렇게 나왔었다.

이유는 orign 주소를 '*' (와일드카드) 로 설정해서 인데 credential 설정을 하면 와일드 카드로 주소를 정해줄수 없다는 의미 였다.

우선 계속 방법을 찾아보다가 백엔드에서 설정 해주면 해결된다는 글을 보고 코드 하나를 추가했더니 해결되었다.

우리 백엔드는 nest로 작성되었다.

main.ts

app.enableCors({
    origin: true,
    credentials: true,
  });

쿠키 때문에 백엔드 에서도 credentials 를 true 로 설정해주었고 orgin을 true로 설정해주었더니 해결되었다.

이게 정확한 방법인지는 모르겠지만 해결되었으니 이 코드를 사용하고 또 오류가 나면 찾아봐야할것같다.

0개의 댓글