node.js學習筆記之MongoDB數據庫

MongoDB相關概念-基於4.0.10的版本

術語 解釋說明
database 數據庫,mongoDB數據庫軟件中能夠創建多個數據庫
collection 集合,一組數據的集合,能夠理解爲JavaScript中的數組
document 文檔,一條具體的數據,能夠理解爲JavaScript中的對象,一個json對象
field 字段,文檔中的屬性名稱,能夠理解爲JavaScript中的對象屬性

Mongoose第三方包

  • 使用Node.js操做MongoDB數據庫須要依賴Node.js第三方包mongoose
  • 使用npm install mongoose命令下載

啓動mongoDB服務

  • 啓動:net start mongodb
  • 中止 net stop mongodb

使用connect鏈接數據庫

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/play',{
    useMongoClient: true,//useMongoClient您能夠在頂層聲明許多聲明和配置,而無需全部額外的嵌套
}).then((db)=>{
    console.log("success")
}).catch(err => console.log(err));
複製代碼

建立集合

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/my_data', {
    useMongoClient: true,//useMongoClient您能夠在頂層聲明許多聲明和配置,而無需全部額外的嵌套
}).then((db) => {
    console.log("success")
    /*console.log(db);*/
}).catch(err => console.log(err));
//建立集合規則
const courseSchema = new mongoose.Schema({
    name: String,
    authors: String,
    isPublic: Boolean
});
//使用規則建立集合,返回的是構造函數
const course = mongoose.model('Course', courseSchema);//數據庫中的集合名字叫作courses
//建立實例文檔
let cou = new course({
    //傳入數據
    name: 'lizeyu',
    authors: 'jkcb',
    isPublic: false
});
//保存到數據庫當中
cou.save().then(r => console.log(r)).catch(err => console.log(err));
複製代碼

建立文檔

建立文檔實際上就是向集合當中插入數據css

//建立文檔的另外一種形式,用回調函數接收錯誤信息和插入的數據
course.create({name:'lihua',authors:'wanghua',isPublic:true},(err,course)=>{
    if (err) console.log(err);
    else console.log(course);
});
//插入數據的操做也是異步的api,能夠用then,catch處理返回的Promise
course.create({
    name: 'lihua',
    authors: 'wanghua',
    isPublic: true
}).then(data => {
    console.log(data);
}).catch(err => console.log(err))
複製代碼

導入數據

使用命令行,使用以前要將mongoimport的命令添加到環境變量當中html

mongoimport -d 數據庫名稱 -c 集合名稱 --file 要導入的數據文件,能夠是json格式相對於當前目錄的位置
複製代碼

查詢文檔

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/my_data', {
    useMongoClient: true,//useMongoClient您能夠在頂層聲明許多聲明和配置,而無需全部額外的嵌套
}).then((db) => {
    console.log("success")
    /*console.log(db);*/
}).catch(err => console.log(err));
const UserSchema = new mongoose. Schema({
    name : String ,
    age : Number ,
    email : String ,
    password: String,
    hobbies: [String]
    });
//使用規則建立集合
const User = mongoose.model('User', UserSchema);//數據庫中集合的名字是users
User.find({name:'張三'}).then((user) => {console.log(user)});//返回一個數組
User.findOne({name:'張三'}).then((user) => {console.log(user)});//返回查詢到的第一條記錄
複製代碼

條件查詢

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/my_data', {
    useMongoClient: true,//useMongoClient您能夠在頂層聲明許多聲明和配置,而無需全部額外的嵌套
}).then((db) => {
    console.log("success")
    /*console.log(db);*/
}).catch(err => console.log(err));
const UserSchema = new mongoose.Schema({
    name: String,
    age: Number,
    email: String,
    password: String,
    hobbies: [String]
});
//使用規則建立集合
const User = mongoose.model('User', UserSchema);//數據庫中集合的名字是users
/*User.find({name: '張三'}).then((user) => {
    console.log(user)
});
User.findOne({name: '張三'}).then((user) => {
    console.log(user)
});*/
User.find({
//大於和小於
    age: {
        $gt: 9,
        $lt: 60
    }, hobbies: {
    //包含
        $in: ['足球']
    }
    //限制前10條,按照年齡升序排列,只展現name和gae hobbies字段
}).limit(10).sort({age:1}).select('name' +
    ' age hobbies').then(result => {console.log(result)});
複製代碼

刪除文檔

//刪除一條
User.deleteOne({name: '張三'}).then((user) => {
    console.log(user)
});
//刪除一個
User.remove({name: '張三'}).then((user) => {
    console.log(user)
});
//刪除多條
User.deleteMany({name:
 '張三'}).then((user) => {
    console.log(user)
});
複製代碼

更新文檔

//傳入查詢條件和要修改的值
User.updateOne({name: '李四'}, {name: '李澤'}).then(result => {
    console.log(result)
});
User.updateMany({name: '李四'}, {name: '李澤'}).then(result => {
    console.log(result)
});
複製代碼

Mongoose驗證

在建立集合規則的時候,能夠設置當前字段的驗證規則,驗證失敗就不能插入,即插入失敗前端

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/my_data', {
    useMongoClient: true,//useMongoClient您能夠在頂層聲明許多聲明和配置,而無需全部額外的嵌套
}).then((db) => {
    console.log("success")
    /*console.log(db);*/
}).catch(err => console.log(err));
const ArticleSchema = new mongoose.Schema({
    title: {
        type: "string",
        //必選屬性
        required: [true,'title is required!!'],
        //最大長度
        maxlength:[6,'length must shorter than 7'],
        //最小長度
        minlength:2,
        //爲了去除字符串前面兩端的空格
        trim:true
    },

});
const Post =  mongoose.model('Article', ArticleSchema);
let pos = new Post({});
pos.save().then((res) => {console.log(res);});
//UnhandledPromiseRejectionWarning: ValidationError: Article validation failed: title: title is required!!
let pos2 = new Post({title:'A'});
pos2.save().then((res) => {console.log(res);});
// UnhandledPromiseRejectionWarning: ValidationError: Article validation failed: title: Path `title` (`A`) is shorter than the minimum allowed length (2).
複製代碼

自定義驗證規則

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/my_data', {
    useMongoClient: true,//useMongoClient您能夠在頂層聲明許多聲明和配置,而無需全部額外的嵌套
}).then((db) => {
    console.log("success")
    /*console.log(db);*/
}).catch(err => console.log(err));
const ArticleSchema = new mongoose.Schema({
    title: {
        type: "string",
        required: [true, 'title is required!!'],
        maxlength: [6, 'length must shorter than 7'],
        minlength: 2,
        //爲了去除字符串前面兩端的空格
        trim: true
    },
    age: {
        type: Number,
        //數值的約束
        default: 18,//默認值
        max: 100,
        min: 1
    },
    publicDate: {
        type: Date,
        default: Date.now(),
    },
    category: {
        type: String,
        enum: ["html", "css"]//枚舉屬性,只能插入該數組內的值
    },
    author: {
        type: String,
        validate: {
            validator: (value) => {
                //自定義驗證器,返回true表示能夠插入,false表明不符合驗證條件
                return value && value.length >= 4;
            },
            message:'傳入的值不符合驗證規則'
        }
    }
});
const Post = mongoose.model('Article', ArticleSchema);
let pos = new Post({
    title: "Aacss",
    age: 55,
    category: 'css',
    author:'liw'
});
pos.save().then((res) => {
    console.log(res);
});
複製代碼

打印自定義錯誤信息

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/my_data', {
    useMongoClient: true,//useMongoClient您能夠在頂層聲明許多聲明和配置,而無需全部額外的嵌套
}).then((db) => {
    console.log("success")
    /*console.log(db);*/
}).catch(err => console.log(err));
const ArticleSchema = new mongoose.Schema({
    title: {
        type: String,
        required: [true, 'title is required!!'],
        maxlength: [6, 'length must shorter than 7'],
        minlength: 2,
        //爲了去除字符串前面兩端的空格
        trim: true
    },
    age: {
        type: Number,
        //數值的約束
        default: 18,//默認值
        max: 100,
        min: 1
    },
    publicDate: {
        type: Date,
        default: Date.now(),
    },
    category: {
        type: String,
        enum:  [["html", "css"],'不在數字內的數據']//枚舉屬性,只能插入該數組內的值

    },
    author: {
        type: String,
        validate: {
            validator: (value) => {
                //自定義驗證器,返回true表示能夠插入,false表明不符合驗證條件
                return value && value.length >= 4;
            },
            message: '傳入的值不符合驗證規則'
        }
    }
});
const Post = mongoose.model('Article', ArticleSchema);
Post.create({
    title: 'aa',
    age: 60,
    category: 'jaa',
    author: 'bd'
}).then(result => console.log(result))
    .catch((error) => {
//獲取錯誤信息對象
            let err = error.errors;
//循環錯誤信息對象
            for (let attr in err) {
                //將錯誤信息打印到控制檯中
                console.log(err[attr]['message']);
            }
        }
    );
複製代碼

集合的關聯查詢

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/my_data', {
    useMongoClient: true,//useMongoClient您能夠在頂層聲明許多聲明和配置,而無需全部額外的嵌套
}).then((db) => {
    console.log("success")
    /*console.log(db);*/
}).catch(err => console.log(err));
const User = mongoose.model("User", new mongoose.Schema({name: String}));

const Post = mongoose.model("Post", new mongoose.Schema({
    title: String,
    //使用id將user和post集合關聯起來
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
}));
//插入數據
/*User.create({name: 'lizey'}).then(result => {console.log(result)});*/
/*Post.create({title: 'wohaole',author:'5ea1752dfe70e8330c517185'});*/
//populate關鍵字實現關聯查詢
Post.find().populate('author').then((result,err) => {console.log(result)})
複製代碼

例子:用戶信息管理

const http = require('http');
const mongoose = require('mongoose');
const url = require('url');
const qs = require('querystring');
const app = http.createServer();
mongoose.connect('mongodb://localhost/my_data', {
    //useMongoClient您能夠在頂層聲明許多聲明和配置,而無需全部額外的嵌套
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(res => {
    console.log('success')
}).catch(err => console.log(err));
const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minLength: 2,
        maxLength: 25
    },
    age: {
        type: Number,
        min: 18,
        max: 80
    },
    password: {
        type: String,
        required: true
    },
    email: {
        type: String
    },
    hobbies: {
        type: [String]
    }
});
const User = mongoose.model('User', UserSchema);
app.on('request', async (req, res) => {
    const method = req.method;
    const {pathname, query} = url.parse(req.url, true);
    if (method === 'GET') {
        if (pathname === '/list') {
            let usersData = await User.find();
            /*        console.log(usersData);*/
            let listPageBefore = `<!DOCTYPE html>
<html lang="en">
<head>
\t<meta charset="UTF-8">
\t<title>用戶列表</title>
\t<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
\t<div class="container">
\t\t<h6>
\t\t\t<a href="/add" class="btn btn-primary">添加用戶</a>
\t\t</h6>
\t\t<table class="table table-striped table-bordered">
\t\t\t<tr>
\t\t\t\t<td>用戶名</td>
\t\t\t\t<td>年齡</td>
\t\t\t\t<td>愛好</td>
\t\t\t\t<td>郵箱</td>
\t\t\t\t<td>操做</td>
\t\t\t</tr>`;
            usersData.forEach(item => {
                listPageBefore += `<tr>
\t\t\t\t<td>${item.name}</td>
\t\t\t\t<td>${item.age}</td>
\t\t\t\t<td>`;
                item.hobbies.forEach((current, index) => {
                    listPageBefore += `\t\t\t\t\t<span>${current}</span>`
                });
                listPageBefore +=
                    `\t\t\t\t</td>
\t\t\t\t<td>${item.email}</td>
\t\t\t\t<td>
\t\t\t\t\t<a href="/delete?id=${item.id}" class="btn btn-danger btn-xs">刪除</a>
\t\t\t\t\t<a href="/modify?id=${item.id}" class="btn btn-success btn-xs">修改</a>
\t\t\t\t</td>
\t\t\t</tr>`
            });
            listPageBefore += `
\t\t</table>
\t</div>
</body>
</html>`;
            res.end(listPageBefore);
        } else if (pathname === '/add') {
            let add = `<!DOCTYPE html>
<html lang="en">
<head>
\t<meta charset="UTF-8">
\t<title>用戶列表</title>
\t<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
\t<div class="container">
\t\t<h3>添加用戶</h3>
\t\t<form method="post" action="/add">
\t\t  <div class="form-group">
\t\t    <label>用戶名</label>
\t\t    <input type="text" class="form-control" placeholder="請填寫用戶名" name="name">
\t\t  </div>
\t\t  <div class="form-group">
\t\t    <label>密碼</label>
\t\t    <input type="password" class="form-control" placeholder="請輸入密碼" name="password">
\t\t  </div>
\t\t  <div class="form-group">
\t\t    <label>年齡</label>
\t\t    <input type="text" class="form-control" placeholder="請填寫郵箱" name="age">
\t\t  </div>
\t\t  <div class="form-group">
\t\t    <label>郵箱</label>
\t\t    <input type="email" class="form-control" placeholder="請填寫郵箱" name="email">
\t\t  </div>
\t\t  <div class="form-group">
\t\t    <label>請選擇愛好</label>
\t\t    <div>
\t\t    \t<label class="checkbox-inline">
\t\t    \t  <input type="checkbox" value="足球"  name="hobbies"> 足球
\t\t    \t</label>
\t\t    \t<label class="checkbox-inline">
\t\t    \t  <input type="checkbox" value="籃球" name="hobbies"> 籃球
\t\t    \t</label>
\t\t    \t<label class="checkbox-inline">
\t\t    \t  <input type="checkbox" value="橄欖球" name="hobbies"> 橄欖球
\t\t    \t</label>
\t\t    \t<label class="checkbox-inline">
\t\t    \t  <input type="checkbox" value="敲代碼" name="hobbies"> 敲代碼
\t\t    \t</label>
\t\t    \t<label class="checkbox-inline">
\t\t    \t  <input type="checkbox" value="抽菸" name="hobbies"> 抽菸
\t\t    \t</label>
\t\t    \t<label class="checkbox-inline">
\t\t    \t  <input type="checkbox" value="喝酒" name="hobbies"> 喝酒
\t\t    \t</label>
\t\t    \t<label class="checkbox-inline">
\t\t    \t  <input type="checkbox" value="燙頭" name="hobbies"> 燙頭
\t\t    \t</label>
\t\t    </div>
\t\t  </div>
\t\t  <button type="submit" class="btn btn-primary" >添加用戶</button>
\t\t</form>
\t</div>
</body>
</html>`;
            res.end(add);
        } else if (pathname === "/modify") {
            let user = await User.findOne({_id: query.id});
            let hobbies = ['足球', '籃球', '抽菸', '喝酒', '敲代碼', '燙頭', '橄欖球'];
            console.log(user);
            let modify = `<!DOCTYPE html>
<html lang="en">
<head>
\t<meta charset="UTF-8">
\t<title>用戶列表</title>
\t<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
\t<div class="container">
\t\t<h3>修改用戶</h3>
\t\t<form method="post" action="/modify?id=${user._id}">
\t\t  <div class="form-group">
\t\t    <label>用戶名</label>
\t\t    <input type="text" class="form-control" placeholder="請填寫用戶名" name="name" value="${user.name}">
\t\t  </div>
\t\t  <div class="form-group">
\t\t    <label>密碼</label>
\t\t    <input type="password" class="form-control" placeholder="請輸入密碼" name="password" value="${user.password}">
\t\t  </div>
\t\t  <div class="form-group">
\t\t    <label>年齡</label>
\t\t    <input value="${user.age}" type="text" class="form-control" placeholder="請填寫郵箱" name="age" >
\t\t  </div>
\t\t  <div class="form-group">
\t\t    <label>郵箱</label>
\t\t    <input type="email" class="form-control" placeholder="請填寫郵箱" name="email" value="${user.email}">
\t\t  </div>
\t\t  <div class="form-group">
\t\t    <label>請選擇愛好</label>
\t\t    <div>`;
            hobbies.forEach((item) => {
                if (user.hobbies.includes(item)) {
                    modify += `\t\t    \t<label class="checkbox-inline">
\t\t    \t  <input type="checkbox" value="${item}"  name="hobbies" checked> ${item}
\t\t    \t</label>`
                } else {
                    modify += `\t\t    \t<label class="checkbox-inline">
\t\t    \t  <input type="checkbox" value="${item}"  name="hobbies"> ${item}
\t\t    \t</label>`
                }
            });
            modify +=
                `            
\t\t    </div>
\t\t  </div>
\t\t  <button type="submit" class="btn btn-primary" >修改用戶</button>
\t\t</form>
\t</div>
</body>
</html>`;
            res.end(modify);
        } else if (pathname === '/delete') {
            let user = await User.findOneAndRemove({_id: query.id});
            console.log(user);
            res.writeHead(301, {
                Location: '/list'
            });
            res.end();
        }
    } else if (method === 'POST') {
        if (pathname === '/add') {
            let formDare = [];
            req.on('data', (data, err) => {
                formDare.push(data);
            });
            req.on('end', async () => {
                let buffer = Buffer.concat(formDare);
                let data = qs.parse(buffer.toString());
                await User.create(data).then((user) => {
                    console.log(user)
                }).catch(err => console.log(err));
                //301表明重定向
                res.writeHead(301, {
                    Location: '/list'
                });
                res.end();
            })
        } else if (pathname === '/modify') {
            let formDare = [];
            req.on('data', (data, err) => {
                formDare.push(data);
            });
            req.on('end', async () => {
                let buffer = Buffer.concat(formDare);
                let data = qs.parse(buffer.toString());
                await User.updateOne({_id: query.id}, data).then((user) => {
                    console.log(user)
                }).catch(err => console.log(err));
                //301表明重定向
                res.writeHead(301, {
                    Location: '/list'
                });
                res.end();
            })
        }
    }
});

app.listen(3000);
複製代碼

使用模板引擎改進用戶信息管理系統-art-template

//app.js
const template = require('art-template');
const path = require('path');
//返回拼接好的字符串html代碼,也就是模板渲染
const html = template(path.join(__dirname, 'index.art'),{
    name:'liz0',
    age:20
});
console.log(html);
//index.art
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<span>{{name}}</span>
<span>{{age}}</span>
</body>
</html>
//輸出
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<span>liz0</span>
<span>20</span>
</body>
</html>
複製代碼

模板語法

輸出

將某項數據輸出在模板中,標準語法和原始語法以下:mongodb

  • 標準語法:{數據}
  • 原始語法:<%=數據%>
  • 數據內部也能夠寫三目運算符

原文輸出

若是數據中攜帶HTML標籤,默認模板引掌不會解析標籤,會將其轉義後輸出。數據庫

  • 標準語法:{@數據}
  • 原始語法:<%-數據%>

條件判斷

在模板中能夠根據條件來決定顯示哪塊HTML代碼。npm

<1--標準語法-->json

  • {(if條件))...{/if}}
  • ((if v1))...(else if v2))...({/if)}

<2--原始語法--> 相似於原生的js語法bootstrap

  • <% if (value) { %> ... <% } %>
  • <% if (v1) { %> ... <% } else if (v2) { %> ... <% } %>
{{if age >18}}
年齡大於18
{{else if age <15}}
年齡小於15
{{else}}
年齡在15-18之間
{{/if}}
複製代碼

循環

{{each 數據}}
    {{$index}} {{$value}}
{{/each}}
<% for(var i = 0; i < 數據.length; i++){ %>
    <%= i %> <%= 數據[i] %>
<% } %>

//例子
<ul>
{{each users}}
<li>
{{$value.name}}
{{$value.age}}
{{$value.sex}}
</1i>
{{/each}}
</u1>
//標準語法相似於js代碼的洗髮
<ul>
<% for (var i = 0; i < users. length; i++){%>
<li>
<%=users[i].name%>
<%=users[i].age %>
<%=users[i].sex%>
</li>
<%}%>
</ul>
複製代碼

變量

標準語法
{{set temp = data.sub.content}}
原始寫法
<% var temp = data.sub.content; %>
複製代碼

子模板

使用子模板能夠將網站公共區塊(頭部、底部)抽離到單獨的文件中。api

  • 標準語法:{{include「模板"}}
  • 原始語法:<%include(模板)%>
<!--標準語法-->
{{include'./header.art'}}
{{include './header.art' data}}
<!--原始語法-->
<% include('./header.art') %>
<% include('./header.art', data) %>
複製代碼

模板繼承

使用模板繼承能夠將網站HTML骨架抽離到單獨的文件中,其餘頁面模板能夠繼承骨架文件,能夠經過在HTML骨架模板中預留一些能夠填充的位置,而後在繼承的時候進行填充達到自定義數組

<!--layout.art-->
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>{{block 'title'}}My Site{{/block}}</title>

    {{block 'head'}}
    <link rel="stylesheet" href="main.css">
    {{/block}}
</head>
<body>
    {{block 'content'}}{{/block}}
</body>
</html>
//繼承填充
<!--index.art-->
{{extend './layout.art'}}

{{block 'title'}}{{title}}{{/block}}

{{block 'head'}}
    <link rel="stylesheet" href="custom.css">
{{/block}}

{{block 'content'}}
<p>This is just an awesome page.</p>
{{/block}}
複製代碼

過濾器 在模板當中調用方法

template.defaults.imports.變量名 = 變量值

//app.js
const template = require('art-template');
const path = require('path');
const dateFormat = require('dateformat');
template.defaults.imports.dateFormat = dateFormat;
//返回拼接好的字符串html代碼
const html = template(path.join(__dirname, 'index.art'),{
    time:new Date()
});
console.log(html);
//index.art
{{dateFormat(time,'yyyy-MM-dd hh:mm:ss')}}
//輸出
2020-39-24 05:04:58
複製代碼

設置根目錄,爲了方便渲染模板

// 模板根目錄。若是 filename 字段不是本地路徑,則在 root 查找模板
template.defaults.root =  你存放全部模板的目錄
該值在系統中的默認值是'/'
設置完成以後傳入template時再也不須要路徑拼接,由於系統會自動去root目錄下找該文件
const html = template('index.art',{
    time:new Date()
});
// 默認後綴名。若是沒有後綴名,則會自動添加 extname
extname: '.art',
能夠本身設置
一樣是template.default.extname = 你但願的後綴名
改爲.html會有代碼書寫的提示
複製代碼

使用模板的信息管理網頁

路由實現請求的管理

功能:實現路由

使用步驟:

  • 1.獲取路由對象
  • 2.調用路由對象提供的方法建立路由
  • 3.啓用路由,使路由生效
const getRouter = require('router')
const router = getRouter ( ) ;
router.get('/add',(req,res)=>{
res.end('Hello world!')
})
server.on('request',(req,res)=>{
router(req,res,()=>{})
})
複製代碼

serve-static實現靜態資源訪問的功能

功能:實現靜態資源訪問服務 步驟:

  • 1.引入serve-static模塊獲取建立靜態資源服務功能的方法
  • 2.調用方法建立靜態資源服務並指定靜態資源服務目錄
  • 3.啓用靜態資源服務功能
const servestatic = require('serve-static')
const serve = servestatic (靜態資源的根目錄)
server.on('request',()=>{
serve(req,res,()=>{})
})
複製代碼

router實現信息管理系統

代碼倉庫

項目目錄結構

//app.js 入口文件 主要是監聽請求和端口
const http = require('http');
const template = require('art-template');
const path = require('path');
const serveStatic = require('serve-static');
const dateFormat = require('dateformat');
template.defaults.imports.dateFormat = dateFormat;
require('./connect.js');
const router = require('./router/index.js');
//實現靜態資源訪問目錄
const serve = serveStatic(path.join(__dirname, 'public'));
template.defaults.root = path.join(__dirname, 'views');
template.defaults.extname = '.html';
const app = http.createServer();
app.on('request', (req, res) => {
    //啓用靜態資源訪問功能
    serve(req, res, () => {
    });
    router(req, res, () => {
    });
});
app.listen(3000);
console.log('服務器啓動成功!!');

//user.js 定義集合約束Schema
const mongoose = require('mongoose');
const studentSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minLength: 2,
        maxLength: 10
    },
    age: {
        type: Number,
        required: true,
        max: 25,
        min: 10
    },
    sex: {
        type: String,
    },
    email: {
        type: String
    },
    hobbies: {
        type: [String],
    },
    college: {
        type: String,
    },
    entryDate: {
        type: Date,
        default: Date.now()
    }
});
const Student = mongoose.model('Student',studentSchema);
module.exports=  Student;

//建立鏈接數據庫
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/my_data', {
    //useMongoClient您能夠在頂層聲明許多聲明和配置,而無需全部額外的嵌套
    useMongoClient:true
}).then(res => {
    console.log('success')
}).catch(err => console.log(err));

//路由文件,監聽get和post請求
const getRouter = require('router');
const router = getRouter();
const template = require('art-template');
const qs = require('querystring');
const Student = require('./../user');
router.get('/add', (req, res) => {
    let index = template('index.html', {});
    //返回增長頁面
    res.end(index)
});
router.get('/list', async (req, res) => {
    let student =  await Student.find();
    console.log(student);
    let list = template('list.html', {
        student:student
    });
    //返回列表頁面
    res.end(list)
});
router.post('/add', (req, res) => {
    let formDare = [];
    req.on('data', (data) => {
        formDare.push(data);
    });
    req.on('end', async () => {
        let buffer = Buffer.concat(formDare);
        let data = qs.parse(buffer.toString());
        await Student.create(data)
        //301表明重定向
        res.writeHead(301, {
            Location: '/list'
        });
        res.end();
    })
});
module.exports = router;

//模板視圖文件 index.html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
	<title>學生檔案</title>
	<link rel="stylesheet" href="./css/main.css">
</head>
<body>
	<form method="post"
		  action="/add">
		<fieldset>
			<legend>學生檔案</legend>
			<label>
				姓名: <input
					class="normal" type="text" autofocus placeholder="請輸入姓名" name="name">
			</label>
			<label>
				年齡: <input
					class="normal"  type="text" placeholder="請輸入年齡" name="age">
			</label>
			<label>
				性別:
				<input
						type="radio" value="0" name="sex"> 男
				<input
						type="radio" value="1" name="sex"> 女
			</label>
			<label>
				郵箱地址:
				<input
						class="normal" type="text" placeholder="請輸入郵箱地址" name="email">
			</label>
			<label>
				愛好:
				<input
						type="checkbox" value="敲代碼" name="hobbies"> 敲代碼
				<input
						type="checkbox" value="打籃球" name="hobbies"> 打籃球
				<input
						type="checkbox" value="睡覺" name="hobbies"> 睡覺
			</label>
			<label>
				所屬學院:
				<select
						class="normal" name="college">
					<option value="前端與移動開發">前端與移動開發</option>
					<option value="PHP">PHP</option>
					<option value="JAVA">JAVA</option>
					<option value="Android">Android</option>
					<option value="IOS">IOS</option>
					<option value="UI設計">UI設計</option>
					<option value="C++">C++</option>
				</select>
			</label>
			<label>
				入學日期:
				<input
						type="date" class="normal" name="entryDate">
			</label>
			<label class="btn">
				<input type="submit" value="提交" class="normal">
			</label>
		</fieldset>
	</form>
</body>
</html>

//list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>學員信息</title>
    <link rel="stylesheet"
          href="./css/list.css">
</head>
<body>
<table>
    <caption>學員信息</caption>
    <tr>
        <th>姓名</th>
        <th>年齡</th>
        <th>性別</th>
        <th>郵箱地址</th>
        <th>愛好</th>
        <th>所屬學院</th>
        <th>入學時間</th>
    </tr>
    {{each student}}
    <tr>
        <th>{{$value
            .name}}
        </th>
        <th>{{$value
            .age}}
        </th>
        <th>{{$value.
            sex ===
			'0'?'男':'女'}}
        </th>
        <th>{{$value
            .email}}
        </th>
        <th>{{each
            $value.hobbies}}
            {{$value}}
            {{/each}}</th>
        <th>{{$value
			.college}}</th>
        <th>{{dateFormat($value
            .entryDate,'yyyy-MM-dd')
            }}</th>
    </tr>
    {{/each}}
</table>
</body>
</html>
複製代碼
相關文章
相關標籤/搜索