Node.js_ express.Router 路由器_模塊化管理路由

路由器 express.Routercss

路由器 模塊化管理 路由html

  • 基本使用:
  • 路由模塊

1. 引入 expressnode

const express = require('express');mongodb

其餘相關模塊數據庫

const sha1 = require('sha1');express

const tableModel= require('models');json

const {resolve} = require(path);promise

2. 建立路由器對象服務器

const router = new express.Router();app

3. 寫 router.post() 或者 router.get()

4. 暴露本模塊的路由

module.exports = router;

  • index.js 主模塊使用 app.use(中間件) 使用

1. 引入路由器模塊

const uiRouter = require('./routers/uiRouter');

const userRouter = require('./routers/userRouter');

2. 應用路由器

app.use(uiRouter);

app.use(userRouter);

  • 源代碼實例(登陸/註冊)

package.json

  • { "name": "node_express", "version": "1.0.0", "main": "index.js", "license": "MIT", "dependencies": { "express": "^4.16.4", "mongoose": "^5.4.0" } }

templates/login.html

  • <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8"/>
            <title>用戶登陸</title>
            
            <link rel="stylesheet" type="text/css" href="css/index.css"/>
        </head>
        
        <body>
            <div id="outer_box" class="login">
                <h2>用戶登陸</h2>
                <form action="http://localhost:3000/login" method="post">
                    <div class="clothes">
                        <label for="input_name">&nbsp;&nbsp;</label>
                        <input id="input_name" type="text" name="user_name" placeholder="請輸入用戶名" />
                    </div>
                    
                    <div class="clothes">
                        <label for="input_pwd">&nbsp;&nbsp;&nbsp;</label>
                        <input id="input_pwd" type="password" name="user_pwd" placeholder="請輸入密碼" />
                    </div>
                    
                    <div class="clothes">
                        <a class="btn" href="http://localhost:3000/register">
                            <button type="button">註冊</button>
                        </a>
                        <button class="login btn" type="submit">登陸</button>
                    </div>
                </form>
            </div>
        </body>
    </html>

templates/register.html

  • <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8"/>
            <title>用戶註冊</title>
            
            <link rel="stylesheet" type="text/css" href="css/index.css"/>
        </head>
        
        <body>
            <div id="outer_box" class="register">
                <h2>用戶註冊</h2>
                <form action="http://localhost:3000/register" method="post">
                    <div class="clothes">
                        <label for="input_name">&nbsp;&nbsp;</label>
                        <input id="input_name" type="text" name="user_name" placeholder="請輸入用戶名" />
                    </div>
            
                    <div class="clothes">
                        <label for="input_pwd">&nbsp;&nbsp;&nbsp;</label>
                        <input id="input_pwd" type="password" name="user_pwd" placeholder="請輸入密碼" />
                    </div>
                    
                    <div class="clothes">
                        <label for="input_repeat_pwd">確認密碼</label>
                        <input id="input_repeat_pwd" type="password" name="user_repeat_pwd" placeholder="請再次輸入密碼" />
                    </div>
                    
                    <div class="clothes">
                        <label for="input_email">註冊郵箱</label>
                        <input id="input_email" type="text" name="user_email" placeholder="請輸入郵箱地址" />
                    </div>
                    
                    <div class="clothes">
                        <button class="register btn" type="submit">註冊</button>
                        <a class="btn" href="http://localhost:3000/login">
                            <button type="button">登陸</button>
                        </a>
                    </div>
                </form>
            </div>
        </body>
    </html>

templates/css/index.css

  • body { width: 100%; height: 100%; color: #000; background: #b9c2a4; background-size: cover; /* 指定背景圖片大小 */
    }
    
    /*************************************************/ #outer_box { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #1a45c3;
    } #outer_box.login { color: #9e098b;
    } #outer_box.register { color: #1a45c3;
    } #outer_box>h2{ padding-bottom: 40px; margin-left: -50px;
    } .clothes { width: 260px; display: flex; justify-content: space-between; margin: 20px 0; font-size: 18px; line-height: 32px;
    } .clothes>label{ width: 80px; text-align: center;
    } .clothes>input{ width: 170px; height: 32px;
    } button { width: 100%; height: 100%; font-size: 16px; background-color: #c4ceda; cursor: pointer;
    } .clothes .btn{ width: 64px; height: 32px; margin: 0 20px;
    } .clothes button.register{ background-color: #1a45c3; color: #fff;
    } .clothes button.login{ background-color: #9e098b; color: #fff;
    }

routers/get/index_router.js

  • const express = require('express'); const {resolve} = require('path'); const indexRouter = new express.Router(); /************************ get ***********************/ indexRouter.get('/', (request, response)=>{ response.sendFile(resolve(__dirname, '../../templates/login.html')); }); indexRouter.get('/login', (request, response)=>{ response.sendFile(resolve(__dirname, '../../templates/login.html')); }); indexRouter.get('/register', (request, response)=>{ response.sendFile(resolve(__dirname, '../../templates/register.html')); }); module.exports = indexRouter;

routers/post/form_router.js

  • const express = require('express'); const sha1 = require('sha1'); const promiseConnect = require('../../db/connectDB.js'); const userInfoModel = require('../../models/userModel.js'); const formRouter = new express.Router(); /************************ post ***********************/ let logged = false ; promiseConnect.then(async result=>{ console.log(result); formRouter.post('/register', async (request, response)=>{ const { user_name:uName, user_pwd:uPwd, user_repeat_pwd:urePwd, user_email:uEmail, } = request.body; /**** 解構賦值 ****/ userInfo = { "userName": uName, "userPassword": uPwd, "userEmail": uEmail }; let errInfo = {}; if(urePwd !== uPwd){ errInfo.repeatPassword = '兩次輸入不一致'; }; if(!(/^[a-zA-Z][a-zA-Z0-9_]{5,20}$/.test(uName))){ errInfo.name = '用戶名不合法'; }; if(!(/^[a-zA-Z0-9_]{6,20}$/.test(uPwd))){ errInfo.password = '密碼不合法'; }; if(!(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(uEmail))){ errInfo.email = '郵箱不合法'; }; const badEmail = await userInfoModel.findOne({"userEmail": uEmail}); if(badEmail){ errInfo.emailRegistered = '郵箱已被註冊'; }; if(errInfo.repeatPassword || errInfo.name || errInfo.password || errInfo.email){ response.send(errInfo); return; }; const fond = await userInfoModel.findOne({"userName": uName}); if(fond){ response.send({"error":'用戶名已被註冊'}); }else{ userInfo.userPassword = sha1(userInfo.userPassword); await userInfoModel.create(userInfo); response.redirect('/login'); // http://localhost:3000/login  }; }); formRouter.post('/login',async (request, response)=>{ logged = false; let uName = request.body['user_name']; let uPwd = request.body['user_pwd']; userInfo = { "userName": uName, "userPassword": uPwd }; if(!(/^[a-zA-Z][a-zA-Z0-9_]{5,20}$/.test(uName))){ logged = false; // 用戶名不存在 }else if(!(/^[a-zA-Z0-9_]{6,20}$/.test(uPwd))){ logged = false; // 密碼錯誤  }; const findName = await userInfoModel.findOne({"userName": uName}); const findPwd = await userInfoModel.findOne({"userPassword": sha1(uPwd)}); if(findName && findPwd){ logged = true; }; response.send(logged?{"success":'登陸成功'}:{"error":'用戶名或密碼錯誤'}); }); }).catch(err=>console.log(err)); module.exports = formRouter;

db/connectDB.js

  • const mongoose = require('mongoose'); module.exports = new Promise((resolve, reject)=>{ mongoose.connect('mongodb://localhost:27017/user_database', {useNewUrlParser:true}) mongoose.connection.once('open', err=>{ if(err){ console.log(err); reject(err); }else{ resolve('數據庫已鏈接'); }; }); });

models/userModel.js

  • const mongoose = require('mongoose'); const Schema = mongoose.Schema; const fieldSchema = new Schema({ "userName": { "type": String, "unique": true, "required": true }, "userPassword": { "type": String, "required": true }, "userEmail": { "type": String, "unique": true, "required": true }, "createTime": { "type": Date, "default": Date.now() } }); module.exports = mongoose.model("user_info", fieldSchema);

index.js

  • const express = require('express'); const app = express(); const indexRouter = require('./routers/get/index_router.js'); const formRouter = require('./routers/post/form_router.js'); /*********************** 中間件 **********************/ // 暴露路由 login.html register.html app.use(express.static('templates')); // 默認調用 next(); // 將 用戶輸入的數據 掛載到 請求體 request.body 上 app.use(express.urlencoded({extended: true})); // 默認調用 next();  app.use(indexRouter); app.use(formRouter); /**************** 端口號 3000, 啓動服務器 ***************/ app.listen(3000, err=>console.log(err?err:'\n\n服務器已啓動: http://localhost:3000\nHunting Happy!'));
相關文章
相關標籤/搜索