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

路由器 express.Router

路由器 模块化管理 路由

  • 基本使用:
  • 路由模块

1. 引入 express

const express = require('express');

其他相关模块

const sha1 = require('sha1');

const tableModel= require('models');

const {resolve} = require(path);

2. 创建路由器对象

const router = new express.Router();

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">  label>
                        <input id="input_name" type="text" name="user_name" placeholder="请输入用户名" />
                    div>
                    
                    <div class="clothes">
                        <label for="input_pwd">   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">  label>
                        <input id="input_name" type="text" name="user_name" placeholder="请输入用户名" />
                    div>
            
                    <div class="clothes">
                        <label for="input_pwd">   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!'));

 

转载于:https://www.cnblogs.com/tianxiaxuange/p/10161568.html

你可能感兴趣的:(json,数据库)