小型案例-学生档案管理系统

目录结构

小型案例-学生档案管理系统_第1张图片


需要导入的模块

  • http
   const http = require('http');
   const app = http.createServer();
   app.on('request', (req, res) => {
     
   });
   app.listen(80);
  • path
const path = require('path');
//可以将路径进行拼接
path.join([path1][, path2][, ...])
//上一级目录的名称
__dirname
  • art-template
    art-template使用方法

  • querystring

const querystring = require('querystring');
//querystring.parse() 方法将 URL 查询字符串 str 解析为键值对的集合。
//例如,查询字符串 'foo=bar&abc=xyz&abc=123' 会被解析为:
{
     
  foo: 'bar',
  abc: ['xyz', '123']
}
  • dateformat
//日期格式化
const dateformat = require('dateformat');
dateformat(你要格式化的时间, 你要格式化的样式);

代码解析:

1. 数据库部分

connect.js

const mongoose = require('mongoose')

//连接数据库,不想看到提示信息,就加上第二个参数 useUnifiedTopology: true
mongoose.connect('mongodb://localhost/playground', {
      useUnifiedTopology: true, useNewUrlParser: true })
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log('数据库连接失败'))

user.js

const mongoose = require('mongoose');

const studentsSchema = new mongoose.Schema({
     
    name: {
     
        type: String,
        required: true,
        minlength: 2,
        maxlength: 10
    },
    age: {
     
        type: Number,
        min: 10,
        max: 25
    },
    sex: {
     
        type: String
    },
    email: String,
    hobbies: [String],
    collage: String,
    enterDate: {
     
        type: Date,
        default: Date.now
    }
})

const Student = mongoose.model('Student', studentsSchema)

//将学生信息集合进行导出
module.exports = Student;

app.js

/*————————————————————引入资源部分开始—————————————————— */
const http = require('http');
const dateformat = require('dateformat');
const path = require('path');


//引入静态资源访问模块
const serveStatic = require('serve-static')
// 实现静态资源访问服务
const serve = serveStatic(path.join(__dirname, 'public'))


//引入模板引擎
const template = require('art-template');
//配置模板根目录
//__dirname用来获取当前文件的绝对路径
template.defaults.root = path.join(__dirname, 'views');
//处理日期格式的方法
template.defaults.imports.dateformat = dateformat;


//导入数据库模块
require('./model/connect.js');
//引入咱们刚才写好的路由器
const router = require('./route/index')

/*————————————————————引入资源部分结束—————————————————— */

const app = http.createServer();

app.on('request', (req, res) => {
     
    //当一个请求结束之后,执行回调函数里面的内容
    //请求结束就是客户端接收到了服务器发来的响应之后或者终断这次请求
    router(req, res, () => {
     })
    //静态资源访问服务,就是css文件之类
    serve(req, res, () => {
      })
});

app.listen(80);

index.js

const getRouter = require('router');
const router = getRouter();

const template = require('art-template');
const querystring = require('querystring');

//导入学生信息集合
const Student = require('../model/user.js');

//呈递学生档案信息页面
router.get('/add', (req, res) => {
     
    let html = template('index.html', {
     });
    res.end(html);
});

//呈递学生档案信息列表页面
router.get('/list', async (req, res) => {
     
    let students = await Student.find();
    let html = template('list.html', {
     
        students: students
    });
    res.end(html);
});

//实现学生信息添加功能路由
router.post('/add', (req, res) => {
     
    let forData = '';
    req.on('data', param => {
     
        forData += param;
    });
    req.on('end', async () => {
     
        await Student.create(querystring.parse(forData))
        res.writeHead(301, {
     
            Location: '/list'
        });
        res.end();
    });
});

//导出路由器
module.exports = router;

index.html


<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>

<body>
    
    <form action="/add" method="post">
        <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 type="text" class="normal" 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="collage">
                    <option value="前端与移动">前端与移动option>
                    <option value="PHP">PHPoption>
                    <option value="JAVA">JAVAoption>
                    <option value="Android">Androidoption>
                    <option value="IOS">IOSoption>
                    <option value="UI设计">UI设计option>
                    <option value="C++">C++option>
                select>
            label>
            <label>
                入学时间:<input type="date" class="normal" name="enterDate">
            label>
            <label class="btn">
                <input type="submit" value="提交" class="normal">
            label>
        fieldset>
    form>
body>

html>

list.html


<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>

<body>
    <table>
        <caption>学员信息caption>
        <tr>
            <th>姓名th>
            <th>年龄th>
            <th>性别th>
            <th>邮箱地址th>
            <th>爱好th>
            <th>所属学院th>
            <th>入学时间th>
        tr>
        {
    {each students}}
        <tr>
            <th>{
    {$value.name}}th>
            <th>{
    {$value.age}}th>
            <th>{
    {$value.sex == '0' ? '男' : '女'}}th>
            <th>{
    {$value.email}}th>
            <th>
                {
    {each $value.hobbies}}
                <span>{
    {$value}}span>
                {
    {/each}}
            th>
            <th>{
    {$value.collage}}th>
            <th>{
    {dateformat($value.enterDate, 'yyyy-mm-dd')}}th>
        tr>
        {
    {/each}}
    table>
body>

html>

github地址

你可能感兴趣的:(Node.js)