[웹] Node.js & React 회원관리 - 2

또여·2021년 6월 15일
0

노드 리액트 강의

목록 보기
2/5

1. mongodb 가입

https://www.mongodb.com/
몽고DB에 가입, 구글계정으로 어렵지 않게 진행

Cluster라는것을 만들어야함


우측에 Create a New Cluster로 새로 생성.
큰 차이는 없어 보이지만,
AWS, Asia-Singapore(Free Tier) 로 선택해서 진행

2. DB로 관리할 Model과 Schema 작성

User.js라는 파일을 생성하고 거기에 mongoose 모듈을 이용해 스키마를 생성

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
    name:{
        type: String,
        maxLength: 50
    },
    email:{
        type: String,
        trim: true, //space를 없애주는
        unique: 1
    },
    password:{
        type: String,
        minLength: 5
    },
    lastname:{
        type: String,
        maxLength: 50
    },
    role:{
        type: Number,
        default: 0
    },
    image: String,
    token:{
        type: String
    },
    tokenExp:{
        type: Number
    }
})

const User = mongoose.model('User', userSchema) //모델로 감싸준다

module.exports = {User}

* 일반적인 DBMS를 마련해두고 하는 방법도 연구해봐야겠다. 이렇게한다 치면, 모든 모델을 소스에서 다 생성해야하는데 그런 관리방식은 없을 것 같은데

3. Body-parser

Client에서 보내는것을 Body-parser라는 Dependency를 통해서 처리할 수 있음

npm install body-parser --save

4. postman

Client가 없을 때, API를 호출하는 테스트 툴
* 반대로 Server가 없을 때, API 호출해서 데이터를 받는 툴은 Mockoon을 이용

5. [POST] register API 작성

Client에서 호출할 API 중 '회원가입'하는 register API를 작성

index.js 에 아래 내용을 추가한다

const bodyParser = require('body-parser')

//www-form-urlencoded, 데이터를 분석해서 가져올수 있게 해줌
app.use(bodyParser.urlencoded({extended: true}));

//json 타입으로 된 내용을 가져와서 처리할수 있게 해줌
app.use(bodyParser.json());


const { User } = require('./server/models/User') //모델로 정의한 user를 가져와서 사용

app.post('/api/users/register', (req, res) => {
    //회원가입시 필요한 정보들을 client에서 가져와
    //DB에 넣어준다.
    const user = new User(req.body)
    user.save((err, userInfo) => {
        if(err) return res.json({ success: false, err})
        return res.status(200).json({
            success: true
        })
    })
})


31라인: save는 mongoDB에 있는 함수

6. postman으로 success:true 받기

postman에 아래와 같이 해주는데,

  • POST 방식
  • localhost:5000/register주소
  • Body에 json형식으로 내용 작성

false가 나더라도 err메세지가 출력되어서, 왜 에러인지 파악이 어렵지 않다

profile
기록 열심히하는 개발자인척

0개의 댓글