Node.js : 회원가입

김가영·2020년 10월 5일
1

Node.js

목록 보기
1/34
post-thumbnail

1. index.js 파일 만들기 : 시작하는 파일

package.json에서

"scripts": {
    "start": "node index.js",  
 }

추가 → 시작하면 index.js 실행

2. install

vs code terminal 에서
npm install express --save
npm install mongoose --save
npm install body-parser --save

express.js : node.js framework
body-parser : Body 데이터를 분석(parse)해서 req.body 로 출력
mongoose : data base

3. 서버 시작하기

npm run start

4. git

SSH : 안전한 통신을 위한.

https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/connecting-to-github-with-ssh


install 써먹기

  • index.js 파일에서
const express = require("express")
const bodyParser = require("body-parser")
const mongoose = require('mongoose')

const app = express()

// application/x-www-form-urlencoded type을 분석해서 가져오도록
app.use(bodyParser.urlencoded({extended : true}));
// application/json 파일을 가져올 수 있도록;
app.use(bodyParser.json())

// mongo  연결되면 'MongoDB connected...' console 에 출력
mongoose.connect('--mongoDb id, pw',{
    useNewUrlParser: true, useUnifiedTopology:true, useCreateIndex:true, useFindAndModify:false
}).then(()=>console.log('MongoDB connected...'))
.catch(err=> console.log(err))

통신 시작

const port = 5000

app.listen(port, ()=> console.log(`Example app listening on port ${port}!`))

모델 만들기

user model, user schema : user 와 관련된 data 를 저장한다.

model 은 schema 를 감싸준다.
schema? 하나 하나의 정보를 지정해줄 수 있도록 하는 것

  • User.js 파일에서
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
	name : {
    	type : String,
        maxlength : 50
    }, ...
})
const User = mongoose.model('User',userSchema)

// 다른 파일에서도 쓸 수 있도록
modules.exports = {User}

회원가입 post

  • index.js에서
const { User } = require("./models/User")

app.post('/register',(req,res)=>{
	// 회원가입시 필요한 정보들을 client 에서 가져오면
  	// 데이터베이스에 이들을 저장
  
  	const user = new User(req.body);
  
	// moongodb method : save() user model 에 저장된 것
    user.save((err, userInfo)=>{
        if(err) return res.json({success: false, err})
        return res.status(200).json({
            success : true
        })
    })
  
}
         

profile
개발블로그

0개의 댓글