수업 정말 잘 듣고 있습니다 :) 양질의 강의 감사드려요.
질문게시판에 있는 거도 다 참고했는데 Postman에 넣어보니
{
"success": false,
"err": {}
}
err의 빈칸이 안없어지네요 ㅠㅠ Users.js 코드를 첨부합니다.
+ console.log("req.body:", req.body)을 해보니
ReferenceError: req is not defined
이렇게 뜨네요. req 정의가 안 됐다고하여, index.js코드도 첨부합니다.
const express = require('express')
const app = express()
const port = 1004
const bodyParser = require('body-parser');
const config = require('./config/key');
const { User } = require("./models/Users");
//application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}));
//application/json
app.use(bodyParser.json());
const mongoose = require('mongoose')
mongoose.connect(config.mongoURI, {
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! nodemon을 적용해써요><'))
app.post('/register', (req, res) => {
//회원가입할 때 필요한 정보들을 client에서 가져오면
//그것들을 데이터 베이스에 넣어준다.
const user = new User(req.body)
//bodyparser가 있기에 가능한 것.
//bcrypt로 암호화하기
user.save((err,userInfo)=> {
if (err) return res.json({success: false, err})
return res.status(200).json({
success: true
})
})
})
//save는 몽고DB에서 온 method
app.listen(port, () => console.log('Example app listening on port ${port}!'))
//0710: req가 정의가 안됐대
//console.log("req.body:", req.body)
--------------------------------------------
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10
const userSchema = mongoose.Schema({
name: {
type: String,
maxlength: 50
},
email: {
type: String,
trim: true,
unique: 1
},
password: {
type: String,
maxlength: 50
},
role: {
type: Number,
default: 0
},
image: String,
token: {
type: String
},
tokenExp: {
type: Number
}
})
userSchema.pre('save', function( next ){
var user = this;
//비밀번호를 암호화 시킨다.
if(user.insModified('password')) {
bcrypt.genSalt(saltRounds, function(err, salt) {
if(err) return next(err)
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err)
user.password = hash
next()
})
})
} else{
next()
}
})
// mongoose에서 가져온거, 저장하기 전에 적용할 함수
const User = mongoose.model('User', userSchema)
module.exports = { User }