1. 點擊 button 按鈕 submit 數據并接收服務端的回應
```js
$('#register_form').on('submit', function (e) {
e.preventDefault() // 禁止點擊默認的跳轉事件
var formData = $(this).serialize() // 獲得表單數據,并序列化,是 string 類型
$.ajax({
url: '/register',
type: 'post',
data: formData,
dataType: 'json', // 把 收到的 json 數據轉為對象
success: function (data) {
var err_code = data.err_code;
if(err_code === 0) {
alert('注冊成功');
} else if (err_code === 1) {
alert('用戶名或郵箱已被使用')
} else if (err_code === 500) {
alert('服務器忙,請稍后重試')
}
}
})
})
```
2. 服務端接收數據,并做出回應
```js
// 提交注冊
router.post('/register', function (req, res) {
// 1. 獲取表單提交的數據
// req.body
// 2. 操作數據庫
// 判斷該用戶是否存在,
// 如果已經存在,不允許注冊
// 如果不存在,注冊新建用戶
// 3. 發送響應
// console.log(req.body);
var body = req.body;
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'
});
})
})
})
```