註冊頁面應用

需求

學習完了資料庫使用,資料驗證,模板渲染,接下來做一個小應用。完整的註冊功能

註冊頁面應用

get登錄檔單

提交到當前表單,資料校驗,驗證邏輯如下

密碼需要大於6位

賬戶是否是郵箱

如果不滿足上面兩個條件,直接返回提示

資料庫中是否存在

如果存在,返回提示“賬號已存在”

如果不存在

建立資料模型物件

同步到資料庫

重定向到登入頁面

步驟

1。註冊頁面,get表單

2。註冊頁面,post表單

get和post通常是一個表單

extends layoutappend headlink(rel=‘stylesheet’, href=‘/stylesheets/register。css’)block content h1= titleform(action=“”, method=“post”) divlabel(for=“account”) 賬號input(type=“text”, name=“account” placeholder=‘請輸入賬號’ requiered=‘true’value=‘’)label(for=“password”) 密碼input(type=“password”, name=“password” placeholder=‘請輸入密碼’ requiered=‘true’value=‘’)button(type=‘submit’) 提交if errors ulfor error in errors li。errorMsg!= error。msg

此處需要注意的是,append head,對應的需要在layout檔案中增加一個head,此處才能append

doctypehtmlhtmlheadblockheadtitle= titlelink(rel=‘stylesheet’, href=‘/stylesheets/style。css’)bodyblockcontent

用到的是pug模板的繼承和擴充套件功能

extends layout的意思擴充套件layout中的內容,也就是在繼承layout的內容的基礎上,再新增我們自己的擴充套件

3。get路由控制

返回一個空模板即可

//註冊 get表單router。get(‘/register’, function(req, res, next) {// 返回一個註冊頁面即可 res。render(‘register_form’,{title:‘註冊頁面’})});

4。post路由控制

//註冊 post表單router。post(‘/register’,//校驗資料[ body(‘account’,‘賬號必須是郵箱’)。isEmail()。custom(async value => {let result = await User。find({‘account’:value})if (result。length!==0) {returnPromise。reject(); } })。withMessage(‘賬號已存在’), body(‘password’,‘密碼必須大於6位’)。isLength({min:6}),],function(req,res,next){//根據校驗結果做出不同處理const errors = validationResult(req)if(!errors。isEmpty()){ res。render(‘register_form’,{title:‘註冊頁面’,errors:errors。array()})return }const user = new User({account:req。body。account,password:req。body。password}) user。save(function(err){if (err) {console。log(‘儲存資料庫失敗’);return next(err); }console。log(‘儲存資料庫成功’);//跳轉登入頁面 res。redirect(‘/login’); })})

難點在於自定義驗證器

5。users表

在影象化面板建立一個新的collection即可

註冊頁面應用

6。user model

const mongoose = require(‘mongoose’);const Schema = mongoose。Schema;// 模式const userSchema = new Schema({account: String,password: String})// 編譯成模型const User = mongoose。model(‘User’,userSchema)// 匯出模型module。exports = User

一個完整的註冊功能就完成了。

00:26