```js
// 提交注冊
router.post('/register', function (req, res) {
// 1. 獲取表單提交的數據
// req.body
// 2. 操作數據庫
// 判斷該用戶是否存在,
// 如果已經存在,不允許注冊
// 如果不存在,注冊新建用戶
// 3. 發送響應
// console.log(req.body);
// 對密碼進行 md5 重復加密
var body = req.body;
body.password = md5(md5(body.password));
User.findOne({
// email: body.email
$or: [ { email: body.email },{ nickname: body.nickname } ]
}, function (err, data) {
if (err) {
return res.status(500).json({
success: false,
message: '服務端錯誤'
});
}
if (data) {
// 郵箱或者昵稱已經存在
return res.status(200).json({
err_code: 1,
message: 'Email or nickname already exists'
})
}
new User(body).save(function (err, user) {
if (err) {
return res.status(500).json({
success: false,
message: 'Server error'
})
}
// Express 提供了一個響應方法:json
// 該方法接收一個對象作為參數,它會自動幫你把對象轉為字符串再發送給瀏覽器
res.status(200).json({
err_code: 0,
message: 'OK'
});
})
})
})
```
