백엔드 연결해서 회원가입 구현하기.

성민개발로그·2022년 1월 9일
0

데이터베이스

목록 보기
5/6

1. 프런트엔드 회원가입 정보를 redux action 으로 정보를 전달 해 주기.

저는 리액트 Next.js 로 프론트엔드를 구현했습니다.
signUpForm.js 컴포넌트 만든후에
이메일, 닉네임, 비밀번호를 정확하게 받은후에 redux 를 통해서 type:SIGN_UP_REQUEST, dispatch 를 해줍니다.

const onSubmit = useCallback(()=>{
          if(checkTems && passwordError) {
              console.log(email,nickname,password);
              dispatch({
                type:SIGN_UP_REQUEST,
                data:{email,nickname,password}
            })
          }
    },[checkTems,passwordError]);

2.redux-saga 를 통해서 백엔드 서버로 전달

function signUpAPI(data) { // 4
  return axios.post('/user', data); // 백엔드 서버로 회원가입정보 전송.
}

function* signUp(action) { // 3
  try {
    const result = yield call(signUpAPI,action.data);//call: 비동기에서 await 같은 개념이다.
    console.log(result);
    yield put({
      type: SIGN_UP_SUCCESS,
      data: action.data,
    });
  } catch (err) {
    yield put({ // redux 액션으로 보내줌. put:dispatch라고 생각하면 편하다.
      type: SIGN_UP_FAILURE,
      data: err.response.data,
    });
  }
}

function* watchSignUp() {
  yield takeLatest(SIGN_UP_REQUEST, signUp);
}

export default function* userSaga() {
  yield all([
	...,
    fork(watchSignUp),
    ...,
  ]);
}

3. 백엔드 및 데이터베이스에서 검사.

const express = require('express');
const bcrypt = require('bcrypt');
const {User} = require('../models'); //모델  models/index 에서 가져오기 
const router = express.Router();



router.post('/',async (req, res, next)=>{
    try{ 
        // 중복된 이메일이 있는지 검사.
    const exitUser = await User.findOne({ //시퀄라이저.js 레코드 조회방법중 하나  비동기 이다.
        where: { 
            email:req.body.email,
        }
    })
    if(exitUser){ // 이메일이 중복이라면.
        return res.status(403).send('이미 사용 중인 아이디입니다.'); // 실패  상태코드 status 403 보통 클라이언트에서 실패일때 403
    }
    // bcrypt 라이브러리로 비밀번호 암호화 해주기 2번째 params 는 숫자가 높을수록 보안이 강력해진다 숫자가 높을수록 암호화하는데 시간이 오래걸림.
    const hashedPassword = await bcrypt.hash(req.body.password, 12); 
    await User.create({  //  서버에서 회원가입 data 보내주고 그 data 를 통해서 User 테이블에 새로운 유저 생성
        email: req.body.email,  // data:{email:"dd@dd",nickname:"ddd",password:"qwer"} => req.body 이렇게 표현이됨.
        nickname: req.body.nickname,
        password: hashedPassword,
    })
    res.status(200).json('ok'); // 성공상태 200
    }catch (error){
        console.log(error);
        next(error); // 에러가 생기면 express 에서 알아서  에러를 한방에 넘겨준다. status:500
    }
});

module.exports = router;

4. app.js 설정

const express = require('express');
const cors = require('cors');
const app = express();
const port = 3065;
const postRouter = require('./routes/post');
const userRouter = require('./routes/user');
const db = require('./models'); // models/index.js 에서 db 가져오기.

db.sequelize.sync()
    .then(()=>{
        console.log('db 연결 성공');
    })
    .catch(console.error);

app.use(cors({  // cors 문제 해결 npm i cors  
    origin: '*', // *: 모든도메인 허용
    credentials: false, // 
}
))


app.use(express.json()); //프론트에서 받은 데이터가 json 형태이먄 json 데이터를 req.body 에 넣어준다.
app.use(express.urlencoded({extended: true})); // 프론트에서 받은 데이터가 form형식 데이터 일때  폼데이터를 req.body 에 넣어준다.


app.use('/post',postRouter);
app.use('/user',userRouter);


app.listen(port, ()=>{
    console.log(`app listening at http://localhost:${port}`);
})

0개의 댓글