📒Body-parser Dependency
> Client가 보내는 데이터(아이디, 비밀번호 등)를 Server에서 받을 수 있게 해줌.
> 그 "정보"들을 req.body로 출력해줌.
📒Postman
> 로그인이나 회원가입 할 때처럼 정보를 보내는 Client 역할.
📒Register Route 만들기
//Register Route
const express = require('express')
const app = express()
const port = 5000
const bodyParser = require('body-parser');
//User 모델 가져오기
const {User} = require('./models/User');
//option1: bodyparser가 client로부터 오는 정보를 server에서 분석해서 가져올 수 있게 해주는 역할
//(application/x-www-form-urlencoded)
app.use(bodyParser.urlencoded({extended: true}));
//(application/json) 형태의 정보를 분석해서 가져올 수 있게 해주는 역할
app.use(bodyParser.json());
const mongoose = require('mongoose')
mongoose.connect('mongodb+srv://nr:zxcv7226@boilerplate.el1fe.mongodb.net/myFirstDatabase?retryWrites=true&w=majority', {
useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false
}).then(()=> console.log('MongoDB Connected...'))
.catch(err=>console.log(err))
app.get('/', (req, res) => {
res.send('Hello World!')
})
//라우트의 endpoint: register
app.post('/register', (req, res) => {
//인스턴스 만들고 정보들을 DB에 넣기.
//req.body안에는 json형태로 회원가입할 때 필요한 정보(client가 보내는)가 들어있음.
const user= new User(req.body)
//mongoDB메소드: 정보들이 user모델에 저장됨.
user.save((err, userInfo) => { //callback function
if(err) return res.json({ success: false, err}) //실패했을 때
return res.status(200).json({ //성공했을 때: status(200)
success: true
})
})
})
//즉, body-parser를 이용해 req.body로 client가 보내는 정보를 받을 수 있음.
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Route를 다 작성한 후, Node SERVER를 실행한다.
📒 POST MAN으로 Register Request 보내기
> POST 형식으로 보냈고, endpoint는 register로 했으므로 POST MAN에서 간단하게 JOSN 형식으로 body 작성하고 Send해보면 "success: true" 문구를 확인할 수 있다.
'Web > Basic (Back-end)' 카테고리의 다른 글
[#6] 비밀 설정 정보 관리 (0) | 2021.06.26 |
---|---|
[#5] Nodemon 설치 (0) | 2021.06.26 |
[#3] SSH를 이용해 GITHUB 연결 (0) | 2021.06.26 |
[#2] MongoDB 연결, Model & Schema (0) | 2021.06.26 |
[#1] Node JS & Express JS로 Back-end 시작하기 (0) | 2021.06.23 |