1. User 모델 생성
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = User = mongoose.model('user', UserSchema);
2.필수적인 데이터 조건에 맞게 들어왔는지 확인.
[check('name', 'Name is required').not().isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check('password', 'Please enter a password with 6 or more characters').isLength({min: 6})
],
3. validationResult() 메서드를 통해 request에 error가 있는지 확인.
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
'validationResult()' 는 express-validator 미들웨어안에 있는 메서드입니다.
4. user 객체 생성 + email 중복 확인
const { name, email, password } = req.body;
try {
let user = await User.findOne({ email });
if (user) {
return res
.status(400)
.json({ errors: [{ msg: 'User already exists' }] });
}
user = new User({
name,
email,
password
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
5. jsonwebtoken 생성
await user.save();
const payload = {
user: {
id: user.id
}
};
jwt.sign(
payload,
config.get('jwtSecret'),
{ expiresIn: 360000 },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
}
);
6. exports
module.exports = router;
routes/api/users.js
const express = require('express');
const router = express.Router();
const gravatar = require('gravatar');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('config');
const { check, validationResult } = require('express-validator');
const normalize = require('normalize-url');
const User = require('../../models/User');
// @route POST api/users
// @desc Register user
// @access Public
router.post(
'/',
[
check('name', 'Name is required')
.not()
.isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
'Please enter a password with 6 or more characters'
).isLength({ min: 6 })
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, password } = req.body;
try {
let user = await User.findOne({ email });
if (user) {
return res
.status(400)
.json({ errors: [{ msg: 'User already exists' }] });
}
const avatar = normalize(
gravatar.url(email, {
s: '200',
r: 'pg',
d: 'mm'
}),
{ forceHttps: true }
);
user = new User({
name,
email,
avatar,
password
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
const payload = {
user: {
id: user.id
}
};
jwt.sign(
payload,
config.get('jwtSecret'),
{ expiresIn: 360000 },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
}
);
module.exports = router;
'express' 카테고리의 다른 글
How to manage of 1:N relationship? mongoose (0) | 2020.05.12 |
---|---|
The process error handling (0) | 2020.05.11 |
express api 분석 1."dependencies" (0) | 2020.05.01 |
Thinkster node.js API 강의 후기. (0) | 2020.05.01 |
routing _express docs (0) | 2020.05.01 |